diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 118fd2c..96fd239 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -92,9 +92,9 @@ $ cargo build -p k0-kernel --features console --offline $ tools/qemu-boot-test.sh # boot under QEMU and check the self-tests ``` -`tools/host-test.sh` runs the tests of `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`, `k0-conin`, `k0-vault` and `k0-term` on any host (354 tests on an AArch64 host, 268 elsewhere). It runs `k0-vault` twice, with and without the algorithm feature `vault-ed25519`, which gives 20 and 11 tests. It runs `k0-term` with and without the vault feature, which gives 24 and 21 tests. The tests of `k0-mm` contain AArch64 inline assembly, so they only run on an AArch64 host (Apple Silicon or Linux arm64). The script runs them for both the 4 KiB and the 16 KiB granule. +`tools/host-test.sh` runs the tests of `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`, `k0-conin`, `k0-slice`, `k0-vault` and `k0-term` on any host (363 tests on an AArch64 host, 277 elsewhere). `k0-slice` has 9 tests: they run the rule that decides whether a tick cuts the running task on a model of the scheduler. It runs `k0-vault` twice, with and without the algorithm feature `vault-ed25519`, which gives 20 and 11 tests. It runs `k0-term` with and without the vault feature, which gives 24 and 21 tests. The tests of `k0-mm` contain AArch64 inline assembly, so they only run on an AArch64 host (Apple Silicon or Linux arm64). The script runs them for both the 4 KiB and the 16 KiB granule. -`tools/qemu-boot-test.sh` boots the debug kernel, checks the boot log line by line in a fixed order, fails on any error marker, and stops QEMU as soon as the root task reports `root: sched tests pass`. Besides the pass lines, it expects `k0: kernel reserve ` before the `k0: untyped ` lines, `k0: idle (waiting for a timeout)` and `root: timeout tests pass` after `root: teardown tests pass`, and `root: kernel reserve tests pass` after `root: revocation tests pass`. Any line that starts with `k0: all tasks` is a failure. It also counts the timer tick lines between `root: teardown tests pass` and `root: timeout tests pass` and wants at least 4, because EL0 has no clock and this is how the lower bound of a timeout is checked. The timeout tests wait for real ticks, so a boot takes about 4 seconds longer than it did before. Set `K0_BOOT_TIMEOUT` (seconds) on slow machines. It reads the serial port, so it needs an image with a console driver. To test an image without console, use `K0_BOOT_MEMLOG`, `K0_BOOT_SERIAL=empty` and `K0_BOOT_CONSOLE_PAGE`, which are described in "Testing an image without console" in [USAGE.md](USAGE.md#testing-an-image-without-console). +`tools/qemu-boot-test.sh` boots the debug kernel, checks the boot log line by line in a fixed order, fails on any error marker, and stops QEMU as soon as the root task reports `root: sched tests pass`. Besides the pass lines, it expects `k0: kernel reserve ` before the `k0: untyped ` lines, `k0: idle (waiting for a timeout)` and `root: timeout tests pass` after `root: teardown tests pass`, and `root: kernel reserve tests pass` after `root: revocation tests pass`. Any line that starts with `k0: all tasks` is a failure. It also counts the timer tick lines between `root: teardown tests pass` and `root: timeout tests pass` and wants at least 4, because EL0 has no clock and this is how the lower bound of a timeout is checked. The timeout tests wait for real ticks, so a boot takes about 4 seconds longer than it did before. The time slice test runs twice (a task that got the CPU by `YIELD`, then one that got it by blocking) and takes about 4 seconds in all where the preemption test it replaced took about 1. It also expects `root: slice test yield pass` and `root: slice test block pass`, in this order, before `root: preempt test pass`. Set `K0_BOOT_TIMEOUT` (seconds) on slow machines. It reads the serial port, so it needs an image with a console driver. To test an image without console, use `K0_BOOT_MEMLOG`, `K0_BOOT_SERIAL=empty` and `K0_BOOT_CONSOLE_PAGE`, which are described in "Testing an image without console" in [USAGE.md](USAGE.md#testing-an-image-without-console). An image with the signing oracle (`vault` or `vault-ed25519`) has two more intended faults, so it prints 8 `k0: task fault` lines instead of 6. Run the test with `K0_BOOT_FAULTS=8` and require `root: oracle tests pass` with `K0_BOOT_REQUIRE`. The boot matrix has the rows `vault`, `vault-max`, `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault` and the static check `vault-symbols` for it, and 76 rows in total on a Mac with HVF and 65 in CI. The rows `input-*` and `term-*` cover console input and the terminal. A terminal image prints two more `k0: task fault` lines (8 without the vault, 10 with it), and `tools/term-test.py ` runs its scripted serial session. [USAGE.md](USAGE.md) describes the rows. diff --git a/CONTRIBUTING_KR.md b/CONTRIBUTING_KR.md index f6dbb2f..6c799e8 100644 --- a/CONTRIBUTING_KR.md +++ b/CONTRIBUTING_KR.md @@ -94,9 +94,9 @@ $ cargo build -p k0-kernel --features console --offline $ tools/qemu-boot-test.sh # QEMU 부팅과 자가 테스트 확인 ``` -`tools/host-test.sh`는 `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`, `k0-conin`, `k0-vault`, `k0-term`의 테스트를 어느 호스트에서나 실행합니다(AArch64 호스트에서 354개, 그 밖에서 268개). `k0-vault`는 알고리즘 feature `vault-ed25519`를 포함한 경우와 포함하지 않은 경우로 두 번 실행하며, 각각 20개와 11개입니다. `k0-term`도 `vault` feature를 포함한 경우와 포함하지 않은 경우로 실행하며, 각각 24개와 21개입니다. `k0-mm` 테스트는 AArch64 인라인 어셈블리를 포함하기 때문에 AArch64 호스트(Apple Silicon 또는 Linux arm64)에서만 실행되며, 스크립트가 4 KiB와 16 KiB 그래뉼 두 구성으로 모두 돌립니다. +`tools/host-test.sh`는 `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`, `k0-conin`, `k0-slice`, `k0-vault`, `k0-term`의 테스트를 어느 호스트에서나 실행합니다(AArch64 호스트에서 363개, 그 밖에서 277개). `k0-slice`는 9개이며, 틱이 실행 중인 태스크를 끊을지 정하는 규칙을 스케줄러 모델로 검사합니다. `k0-vault`는 알고리즘 feature `vault-ed25519`를 포함한 경우와 포함하지 않은 경우로 두 번 실행하며, 각각 20개와 11개입니다. `k0-term`도 `vault` feature를 포함한 경우와 포함하지 않은 경우로 실행하며, 각각 24개와 21개입니다. `k0-mm` 테스트는 AArch64 인라인 어셈블리를 포함하기 때문에 AArch64 호스트(Apple Silicon 또는 Linux arm64)에서만 실행되며, 스크립트가 4 KiB와 16 KiB 그래뉼 두 구성으로 모두 돌립니다. -`tools/qemu-boot-test.sh`는 디버그 커널을 부팅하고 부팅 로그를 정해진 순서대로 한 줄씩 확인합니다. 에러 표식이 하나라도 나오면 실패하고, 루트 태스크가 `root: sched tests pass`를 출력하면 곧바로 QEMU를 종료합니다. 통과 줄 외에도 `k0: untyped ` 줄보다 앞의 `k0: kernel reserve `, `root: teardown tests pass` 뒤의 `k0: idle (waiting for a timeout)`와 `root: timeout tests pass`, `root: revocation tests pass` 뒤의 `root: kernel reserve tests pass`를 기대합니다. `k0: all tasks`로 시작하는 줄은 모두 실패입니다. `root: teardown tests pass`와 `root: timeout tests pass` 사이의 타이머 틱 줄도 세어 4개 이상을 요구하는데, EL0에는 시계가 없어서 이것이 타임아웃의 하한을 확인하는 방법이기 때문입니다. 타임아웃 테스트는 실제 틱을 기다리므로 부팅 한 번이 이전보다 약 4초 더 걸립니다. 느린 환경에서는 `K0_BOOT_TIMEOUT`(초)을 늘려 주세요. 직렬 포트를 읽기 때문에 콘솔 드라이버가 있는 이미지가 필요합니다. 콘솔 없는 이미지를 시험하려면 [USAGE_KR.md](USAGE_KR.md#콘솔-없는-이미지-시험)의 "콘솔 없는 이미지 시험"에 설명된 `K0_BOOT_MEMLOG`, `K0_BOOT_SERIAL=empty`, `K0_BOOT_CONSOLE_PAGE`를 사용하세요. +`tools/qemu-boot-test.sh`는 디버그 커널을 부팅하고 부팅 로그를 정해진 순서대로 한 줄씩 확인합니다. 에러 표식이 하나라도 나오면 실패하고, 루트 태스크가 `root: sched tests pass`를 출력하면 곧바로 QEMU를 종료합니다. 통과 줄 외에도 `k0: untyped ` 줄보다 앞의 `k0: kernel reserve `, `root: teardown tests pass` 뒤의 `k0: idle (waiting for a timeout)`와 `root: timeout tests pass`, `root: revocation tests pass` 뒤의 `root: kernel reserve tests pass`를 기대합니다. `k0: all tasks`로 시작하는 줄은 모두 실패입니다. `root: teardown tests pass`와 `root: timeout tests pass` 사이의 타이머 틱 줄도 세어 4개 이상을 요구하는데, EL0에는 시계가 없어서 이것이 타임아웃의 하한을 확인하는 방법이기 때문입니다. 타임아웃 테스트는 실제 틱을 기다리므로 부팅 한 번이 이전보다 약 4초 더 걸립니다. 시간 조각 테스트는 두 번(`YIELD`로 CPU를 받은 태스크, 기다림으로 받은 태스크) 실행해 합계 약 4초가 걸리며, 이를 대신한 이전 선점 테스트는 약 1초가 걸렸습니다. `root: preempt test pass`보다 앞에 `root: slice test yield pass`와 `root: slice test block pass`가 이 순서로 나오는 것도 기대합니다. 느린 환경에서는 `K0_BOOT_TIMEOUT`(초)을 늘려 주세요. 직렬 포트를 읽기 때문에 콘솔 드라이버가 있는 이미지가 필요합니다. 콘솔 없는 이미지를 시험하려면 [USAGE_KR.md](USAGE_KR.md#콘솔-없는-이미지-시험)의 "콘솔 없는 이미지 시험"에 설명된 `K0_BOOT_MEMLOG`, `K0_BOOT_SERIAL=empty`, `K0_BOOT_CONSOLE_PAGE`를 사용하세요. 서명 오라클이 있는 이미지(`vault` 또는 `vault-ed25519`)는 일부러 일으키는 폴트가 두 번 더 있어 `k0: task fault` 줄이 6개가 아니라 8개이므로 `K0_BOOT_FAULTS=8`이 필요하고, `root: oracle tests pass`를 `K0_BOOT_REQUIRE`로 요구하세요. 부팅 매트릭스에는 이를 위한 행 `vault`, `vault-max`, `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`와 정적 검사 `vault-symbols`가 있으며, 행렬은 HVF가 있는 Mac에서 76행, CI에서 65행입니다. 행 `input-*`와 `term-*`는 콘솔 입력과 터미널을 다룹니다. 터미널 이미지는 `k0: task fault` 줄이 두 개 더 나오며(볼트 없이 8개, 볼트와 함께 10개), `tools/term-test.py <이미지>`가 정해진 직렬 세션을 실행합니다. 행의 내용은 [USAGE_KR.md](USAGE_KR.md)에 있습니다. diff --git a/Cargo.lock b/Cargo.lock index 3d65e9b..c65ce7c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -194,9 +194,14 @@ version = "0.1.0" dependencies = [ "k0-arch", "k0-mm", + "k0-slice", "k0-task", ] +[[package]] +name = "k0-slice" +version = "0.1.0" + [[package]] name = "k0-task" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 01efbac..78be90f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ members = [ "crates/k0-abi", "crates/k0-efi", "crates/k0-conin", + "crates/k0-slice", "userspace/root-task", "userspace/k0-vault", "userspace/k0-term", @@ -31,6 +32,7 @@ default-members = [ "crates/k0-abi", "crates/k0-efi", "crates/k0-conin", + "crates/k0-slice", "userspace/root-task", ] diff --git a/INTRODUCTION.md b/INTRODUCTION.md index c8499ce..1b3c6d3 100644 --- a/INTRODUCTION.md +++ b/INTRODUCTION.md @@ -131,7 +131,7 @@ These features only add and are not in `default`, so **every build command must - Address spaces (AddrSpace) Memory is placed on an address space's map only by showing that address space's key (MAP, UNMAP). Keys carry rights (read, write, execute). A mailbox key can carry a tag that tells the receiver who sent a message (badge). Keys can be copied with the same or fewer rights, or moved between slots (CAP_COPY, CAP_MOVE). -- **Running tasks**: a task is tied to one key ring and one address space when it is set up (TCB_CONFIGURE) and then started (TCB_RESUME). Tasks take turns, and a timer interrupts a task that runs too long (round-robin scheduling with timer preemption). A task can give up its turn (YIELD) or finish (EXIT). +- **Running tasks**: a task is tied to one key ring and one address space when it is set up (TCB_CONFIGURE) and then started (TCB_RESUME). Tasks take turns, and a timer interrupts a task that runs too long (round-robin scheduling with timer preemption). A task that was switched in between two timer ticks gets a full period: the first tick it meets does not cut it, so it runs at least one period and at most two before the timer takes the CPU away. This stops a task from using `YIELD` shortly before a tick to shorten the turn of the next task. A task can give up its turn (YIELD) or finish (EXIT). - **Messages**: tasks exchange short messages that travel in processor registers. The sender waits until the receiver takes the message (synchronous IPC: SEND, RECV, CALL, REPLY_RECV). Sending needs the write right on the mailbox key and receiving needs the read right. The receiver learns the tag of the sender's key, and the right to reply can be used only once. - **Timeouts**: every one of these calls can carry a time limit, counted in timer ticks (one tick is one second). If no partner arrives in time, the call returns an error (`TIMEOUT`, or `REPLY_TIMEOUT` when a `CALL` was delivered but no reply came). Without a limit a task waits as long as it takes. The wait lasts at least the given number of ticks and may be a little longer. The limit says when the task becomes ready again, not when it runs. - **Idle**: when no task can run, the kernel no longer stops. It waits for the next interrupt, wakes tasks whose time limit has passed and carries on. If nothing can ever wake a task, the machine stays idle and the boot log says `k0: all tasks stopped (none ready, no timeout pending)`. That line appears only when there is neither a timed waiter nor a task waiting for console input. A terminal image prints nothing there, because waiting for input is its normal state. @@ -270,13 +270,14 @@ What it does not stop: Still open: - A task that waits without a timeout can wait forever if its partner never acts. Timeouts are used per call, so a server that must stay responsive has to give one on every wait. - - There is no priority and no CPU budget. Tasks take turns in equal slices, and a task that holds a lot of free memory can create many tasks and shrink everyone else's share. + - There is no priority and no CPU budget. Tasks take turns, and a task that holds a lot of free memory can create many tasks and shrink everyone else's share. A task that never yields or blocks keeps at least 1/N of the CPU among N ready tasks in the long run. This was checked in a model by search with up to 6 tasks and by tests on the host, it is not proven, and N grows with every task that is created. + - The scheduler leaks timing. A task still changes when, and for how long, another task runs by choosing when to yield or block. This has not been analysed. K0 gives no real-time or latency promise: the tick is one second and the kernel cannot be interrupted. The one-to-two periods per turn describe this version, not an interface. - The kernel cannot be interrupted while it handles a system call. A long call, such as taking back a key to a large block of memory, delays every other task and every timeout. - A fatal error inside the kernel, or an error from the hardware that the kernel cannot attribute to one task, still stops the whole machine. - The kernel part of the boot log can be filled up by crash and exit lines. - The signing oracle is no exception: clients share one mailbox to the vault and must give a timeout on every call, or a stuck vault holds them up. - In an image with input, an outside party can cause interrupts while tasks run. Their number is bounded by the reader, but the reader learns arrival times finer than a timer tick, and other tasks can notice the stolen time. This timing channel has not been analysed. - - Input waits behind the running tasks. There are no priorities, so the delay is up to one tick for each ready task. + - Input waits behind the running tasks. There are no priorities, so the delay is up to one tick for each ready task, plus one more tick when the running task was switched in between two ticks. - The receive code runs in the kernel (EL1). It is small and never interprets a byte, but it is kernel code driven by an outside party. Moving it to a user-space driver needs delegation of devices and interrupts, which K0 does not have yet. - **Tasks that share a key ring and an address space**: such tasks are not isolated from each other. They behave like threads, parts of one program that share everything. - **Control of a task**: whoever holds the key to a task, to its key ring or to its address space controls that task. @@ -342,12 +343,13 @@ In the following table, you can find the contents of each path in the repository | `crates/k0-abi` | System call numbers, error codes and the boot information layout that programs share with the kernel | | `crates/k0-arch` | Handling of errors, system calls and interrupts (exceptions), entering and leaving user mode, interrupt controller and timer, PAC and PAN, the boot log and the optional console drivers | | `crates/k0-conin` | The receive logic of console input (the ring and the loss mark), tested on the host with a fake UART | +| `crates/k0-slice` | The rule that decides whether a timer tick cuts the running task, tested on the host with a model of the scheduler | | `crates/k0-boot` | Device tree parser, the built-in root task image and its integrity check, PAC key derivation, the search for the boot memory window (shared with the loader) | | `crates/k0-efi` | The loader's logic without `unsafe` code: planning RAM from the UEFI memory map, rewriting the firmware device tree, an independent re-check of the result, and the check of the kernel image header. It runs the kernel's own device tree code on the result before the jump | | `crates/k0-cap` | Keys and their rights, key rings, the derivation list, untyped memory, retype, revoke and delete | | `crates/k0-mm` | Kernel page tables, turning memory maps on (MMU), program address spaces and their registry | | `crates/k0-task` | Tasks with their key ring and address space, mailboxes, loading the root task | -| `crates/k0-sched` | Round-robin scheduler | +| `crates/k0-sched` | Round-robin scheduler, which asks `k0-slice` at every tick | | `crates/k0-ipc` | Synchronous messages | | `loader/` | The UEFI application (`k0-loader`, target `aarch64-unknown-uefi`) that embeds a built kernel image and starts it: UEFI calls, the flow, and the final cache flush, MMU off and jump | | `userspace/root-task` | The first program and its self-tests, and the wiring and self-test of the signing oracle (`oracle.rs`), and the start of the terminal service (`service.rs`) | diff --git a/INTRODUCTION_KR.md b/INTRODUCTION_KR.md index f675685..0ba85cd 100644 --- a/INTRODUCTION_KR.md +++ b/INTRODUCTION_KR.md @@ -131,7 +131,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - 주소 공간(AddrSpace) 메모리는 그 주소 공간의 열쇠를 보여 줘야만 그 주소 공간의 지도에 올릴 수 있습니다(MAP, UNMAP). 열쇠에는 권한(읽기, 쓰기, 실행)이 있습니다. 우편함 열쇠에는 누가 보냈는지 받는 쪽에 알려 주는 표식(배지)을 붙일 수 있습니다. 열쇠는 권한을 그대로 두거나 줄여서 복사하거나, 다른 슬롯으로 옮길 수 있습니다(CAP_COPY, CAP_MOVE). -- **태스크 실행**: 태스크는 준비할 때 열쇠고리 하나와 주소 공간 하나에 묶이고(TCB_CONFIGURE) 그다음 시작됩니다(TCB_RESUME). 태스크는 차례를 돌아가며 실행되고, 너무 오래 도는 태스크는 타이머가 끊습니다(타이머 선점이 있는 라운드 로빈 스케줄링). 태스크는 자기 차례를 양보하거나(YIELD) 끝낼 수 있습니다(EXIT). +- **태스크 실행**: 태스크는 준비할 때 열쇠고리 하나와 주소 공간 하나에 묶이고(TCB_CONFIGURE) 그다음 시작됩니다(TCB_RESUME). 태스크는 차례를 돌아가며 실행되고, 너무 오래 도는 태스크는 타이머가 끊습니다(타이머 선점이 있는 라운드 로빈 스케줄링). 두 타이머 틱 사이에 실행을 넘겨받은 태스크는 한 주기를 온전히 받습니다. 처음 만나는 틱은 그 태스크를 끊지 않으므로, 타이머가 CPU를 빼앗기 전에 최소 한 주기, 많아야 두 주기을 실행합니다. 이렇게 해서 태스크가 틱 직전에 `YIELD`를 호출해 다음 태스크의 차례를 줄이는 일을 막습니다. 태스크는 자기 차례를 양보하거나(YIELD) 끝낼 수 있습니다(EXIT). - **메시지**: 태스크는 프로세서 레지스터에 담긴 짧은 메시지를 주고받습니다. 보내는 쪽은 받는 쪽이 메시지를 가져갈 때까지 기다립니다(동기 IPC: SEND, RECV, CALL, REPLY_RECV). 보내려면 우편함 열쇠에 쓰기 권한이, 받으려면 읽기 권한이 있어야 합니다. 받는 쪽은 보낸 쪽 열쇠의 표식을 알게 되고, 답장할 권리는 한 번만 사용할 수 있습니다. - **타임아웃**: 이 호출들은 모두 제한 시간을 줄 수 있습니다. 단위는 타이머 틱입니다(1틱은 1초). 제한 시간 안에 상대가 오지 않으면 호출이 오류(`TIMEOUT`, 또는 `CALL`이 전달됐지만 답이 오지 않은 경우 `REPLY_TIMEOUT`)로 돌아옵니다. 제한 시간을 주지 않으면 태스크는 필요한 만큼 계속 기다립니다. 기다리는 시간은 준 틱 수 이상이며 조금 더 길 수 있습니다. 제한 시간은 태스크가 다시 준비 상태가 되는 때를 정할 뿐, 실행되는 때를 정하지는 않습니다. - **대기 상태**: 실행할 수 있는 태스크가 없어도 커널은 더 이상 멈추지 않습니다. 다음 인터럽트를 기다리다가, 제한 시간이 지난 태스크를 깨우고 계속 진행합니다. 태스크를 깨울 수 있는 것이 아무것도 없으면 기계는 대기 상태로 남고, 부트 로그에 `k0: all tasks stopped (none ready, no timeout pending)`이 찍힙니다. 시간 제한이 걸린 대기도, 콘솔 입력을 기다리는 태스크도 없을 때만 이 줄이 찍힙니다. 터미널 이미지는 입력을 기다리는 것이 정상이라 아무것도 출력하지 않습니다. @@ -271,13 +271,14 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. 아직 열려 있는 부분은 다음과 같습니다. - 타임아웃 없이 기다리는 태스크는 상대가 끝내 행동하지 않으면 영원히 기다릴 수 있습니다. 타임아웃은 호출마다 주는 것이라서, 계속 응답해야 하는 서버는 모든 대기에 타임아웃을 줘야 합니다. - - 우선순위와 CPU 예산이 없습니다. 태스크는 같은 길이의 시간 조각으로 돌아가며 실행되고, 빈 메모리를 많이 가진 태스크는 태스크를 많이 만들어 다른 태스크의 몫을 줄일 수 있습니다. + - 우선순위와 CPU 예산이 없습니다. 태스크는 돌아가며 실행되고, 빈 메모리를 많이 가진 태스크는 태스크를 많이 만들어 다른 태스크의 몫을 줄일 수 있습니다. 양보하거나 기다리지 않는 태스크는 준비된 태스크가 N개일 때 오래 보면 CPU의 1/N 이상을 가집니다. 이는 최대 6개 태스크까지 모델에서 탐색으로 확인하고 호스트 테스트로 검사한 것이며, 증명한 것이 아니고, 태스크를 만들 때마다 N이 커집니다. + - 스케줄러를 통한 타이밍 채널이 열려 있습니다. 태스크는 양보하거나 기다릴 시점을 골라 다른 태스크가 언제, 얼마나 오래 실행되는지를 여전히 바꿀 수 있습니다. 이는 분석하지 않았습니다. K0는 실시간 또는 지연 시간에 대한 약속을 하지 않습니다. 틱은 1초이고 커널은 중단할 수 없습니다. 한 번에 한 주기에서 두 주기라는 값은 이 버전의 동작이며 인터페이스가 아닙니다. - 커널은 시스템 콜을 처리하는 동안 중단할 수 없습니다. 큰 메모리 블록의 열쇠를 회수하는 것 같은 긴 호출은 다른 모든 태스크와 모든 타임아웃을 늦춥니다. - 커널 안의 치명적 오류, 또는 커널이 한 태스크의 탓으로 돌릴 수 없는 하드웨어 오류는 여전히 기계 전체를 멈춥니다. - 부트 로그의 커널 부분은 충돌과 종료 줄로 가득 찰 수 있습니다. - 서명 오라클도 예외가 아닙니다. 클라이언트는 볼트로 가는 우편함 하나를 함께 사용하므로 모든 호출에 타임아웃을 줘야 하며, 그렇지 않으면 멈춘 볼트가 클라이언트를 붙잡습니다. - 입력을 켠 이미지에서는 바깥 쪽이 태스크가 실행되는 동안에도 인터럽트를 일으킬 수 있습니다. 그 횟수는 읽는 쪽 속도로 제한되지만, 읽는 태스크는 타이머 틱보다 더 잘게 도착 시각을 알 수 있고 다른 태스크도 빼앗긴 시간을 눈치챌 수 있습니다. 이 시간 채널은 분석하지 않았습니다. - - 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없어서 지연은 준비된 태스크마다 최대 한 틱입니다. + - 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없어서 지연은 준비된 태스크마다 최대 한 틱이며, 실행 중인 태스크가 두 틱 사이에 실행을 넘겨받았다면 한 틱이 더해집니다. - 입력 수신 코드는 커널(EL1)에서 실행됩니다. 작고 바이트를 해석하지 않지만, 바깥 쪽이 움직이는 커널 코드입니다. 이것을 사용자 공간 드라이버로 옮기려면 장치와 인터럽트를 넘겨 주는 기능이 필요한데, K0에는 아직 없습니다. - **열쇠고리와 주소 공간을 함께 사용하는 태스크**: 이런 태스크끼리는 격리되지 않습니다. 모든 것을 함께 사용하는 한 프로그램의 일부, 즉 스레드처럼 동작합니다. - **태스크 통제**: 어떤 태스크나 그 태스크의 열쇠고리, 주소 공간의 열쇠를 가진 쪽이 그 태스크를 통제합니다. @@ -343,12 +344,13 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. | `crates/k0-abi` | 프로그램과 커널이 함께 사용하는 시스템 콜 번호, 에러 코드, 부팅 정보 레이아웃 | | `crates/k0-arch` | 에러, 시스템 콜, 인터럽트 처리(예외), 사용자 모드 진입과 복귀, 인터럽트 컨트롤러와 타이머, PAC과 PAN, 부트 로그와 선택적 콘솔 드라이버 | | `crates/k0-conin` | 콘솔 입력의 수신 논리(링과 유실 표시). 가짜 UART로 호스트에서 테스트합니다 | +| `crates/k0-slice` | 타이머 틱이 실행 중인 태스크를 끊을지 정하는 규칙. 스케줄러 모델로 호스트에서 테스트합니다 | | `crates/k0-boot` | 디바이스 트리 파서, 내장된 루트 태스크 이미지와 무결성 검사, PAC 키 파생, 부트 메모리 창 탐색(로더와 공유) | | `crates/k0-efi` | `unsafe` 없는 로더의 논리. UEFI 메모리 맵에서 RAM 계획, 펌웨어 디바이스 트리 고쳐 쓰기, 결과의 독립적인 재검사, 커널 이미지 헤더 검사. 점프 전에 결과에 커널 자신의 디바이스 트리 코드를 돌려 봅니다 | | `crates/k0-cap` | 열쇠와 권한, 열쇠고리, 파생 목록, untyped 메모리, retype, revoke와 delete | | `crates/k0-mm` | 커널 페이지 테이블, 메모리 지도 켜기(MMU), 프로그램 주소 공간과 그 등록부 | | `crates/k0-task` | 열쇠고리와 주소 공간에 묶인 태스크, 우편함, 루트 태스크 적재 | -| `crates/k0-sched` | 라운드 로빈 스케줄러 | +| `crates/k0-sched` | 라운드 로빈 스케줄러. 틱마다 `k0-slice`에 묻습니다 | | `crates/k0-ipc` | 동기 메시지 | | `loader/` | 빌드된 커널 이미지를 품고 시작시키는 UEFI 응용 프로그램(`k0-loader`, 타겟 `aarch64-unknown-uefi`). UEFI 호출, 흐름, 마지막의 캐시 비우기·MMU 끄기·점프 | | `userspace/root-task` | 첫 프로그램과 자가 테스트, 서명 오라클의 연결과 자가 테스트(`oracle.rs`), 터미널 서비스의 시작(`service.rs`) | diff --git a/SECURITY.md b/SECURITY.md index edd1d86..2264d96 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -63,7 +63,12 @@ What is still NOT provided on `main`: - **Availability**: isolation does not cover it. The kernel no longer halts when every task is blocked, a task can bound its own waits with a timeout (GHSA-q99x-2wrv-358p, see "Known advisories"), and the two kernel tables for alias mappings and address spaces can no longer be exhausted. The following is still open: - A task that waits without a timeout can wait forever if its partner never acts. A timeout is opt-in per call, so a server or the root task that must stay responsive has to give a timeout on every wait. - - A timeout says when a task becomes ready, not when it runs. There is no priority and no CPU budget. The scheduler is round-robin with a one-tick slice, and a task that holds `Untyped` memory can create many tasks and dilute the share of every other task. + - A timeout says when a task becomes ready, not when it runs. There is no priority and no CPU budget: a CPU-bound task uses its whole turn and nothing caps it. The scheduler is round-robin with a tick of one second. A task that holds `Untyped` memory can create many tasks and dilute the share of every other task, because with N ready tasks the bound below is 1/N and N grows with every task created. + - Taking the CPU from the next task by yielding or blocking just before the tick is addressed on `main`. `YIELD` needs no capability, and before this change the next task then got only the rest of that period, while the yielding task was back at the head of the queue for the next full period (two CPU-bound tasks in QEMU: the other task fell from about 52 % to 8 % to 11 % of the CPU, and to 3.5 % when the kernel measured time with the counter). The rule now: a task that gets the CPU between two ticks (the previous task yielded, blocked, exited or was killed, or the kernel was idle and woke up for something other than a tick) is not preempted by the first tick it meets. A task is therefore not cut before it has run one full period, and a task that never yields or blocks keeps at least 1/N of the CPU with N ready tasks. That bound was checked by search in a model of the scheduler (up to 6 tasks) and by host tests (`crates/k0-slice`), and it was seen in QEMU (with the attacker yielding at 90 % of the period, the other task had 53.8 % to 54.9 %). It is not a proof and not a budget. A self-test at every boot (`root: slice test yield pass`, `root: slice test block pass`) checks that such a task is not cut at its first tick, on the yield path and on the block path. + - Timing channels through the scheduler are open. A task still changes when, and now also for how long, another task runs by choosing when to yield or block. This has not been analysed, and closing it would need fixed time partitions, which K0 does not have. + - There is no real-time or latency promise. The kernel is not preemptible and the tick is one second. A task that becomes ready with k tasks to run before it (the running one included) now starts within k + 1 tick periods, where it used to start within k, so a wait can be up to one tick longer. A caller and a server that exchange calls behind one CPU-bound task needed 2 ticks per round trip in the model and need 4 now. A run of one to two periods and a wait of k + 1 periods describe this version of the scheduler and are not an interface. + - Some mistakes in connecting the rule to the scheduler would be seen by no test on the real kernel: the tick's own switch passing the wrong entry kind, the idle loop reporting the wrong thing about a tick, and the entry kind at the hand-off to the root task. They change how long a task runs before it is cut, not its share. The host model covers the rule for these cases, not the kernel's use of it. The boot test does catch the old rule and a wrong entry kind on the yield path or the block path. + - The measurements used an attacker whose yield point was set for it from a loop count that the root task measured. What an attacker needs to find that point by itself was not measured. Everything ran in QEMU (TCG and HVF), nothing on hardware. - The kernel is not preemptible. A long system call, for example `CAP_REVOKE` on an `Untyped` with many objects, delays every other task and every timeout. - A `k0_arch::fatal` or a kernel panic still stops the machine, and so does an SError taken from EL0. - The kernel part of the boot log can be filled by fault and exit lines. @@ -211,7 +216,7 @@ The limits are as follows: 1. The serial line is as trusted as whoever can reach it. The operator can erase the key, which is a denial of service by design. 2. The kernel's receive code runs at EL1. It is small and never interprets bytes, but it is kernel code driven by an outside party. A user-space driver needs device and interrupt delegation, which K0 does not have. 3. 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. This is a timing channel that has not been analysed. -4. Input waits behind running tasks. There are no priorities, so the latency is up to a tick per ready task. +4. Input waits behind running tasks. There are no priorities, so the latency is up to a tick per ready task, plus one more tick when the running task got the CPU between two ticks. 5. A 16550 console has no input. The SBSA UART path, FIFO overruns and the receive timeout interrupt are not exercised by QEMU, and host tests with a fake UART (`crates/k0-conin`) are their only coverage. The cut-off for an interrupt line that fires without a UART cause is covered by host tests only. 6. No test measures kernel time under a flood on a machine. The bound is argued from the gate and shown in host tests. 7. "Dropped before the prompt" counts bytes that reached the UART. An emulator or adapter that holds bytes back delivers them later, and QEMU does. diff --git a/SECURITY_KR.md b/SECURITY_KR.md index 29a5b96..27b5b33 100644 --- a/SECURITY_KR.md +++ b/SECURITY_KR.md @@ -63,7 +63,12 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다. - **가용성**: 격리는 가용성을 다루지 않습니다. 모든 태스크가 블록되어도 커널은 더 이상 멈추지 않고, 태스크는 타임아웃으로 자신의 대기를 제한할 수 있으며(GHSA-q99x-2wrv-358p, "알려진 어드바이저리" 참고), 별칭 매핑과 주소 공간을 위한 두 커널 테이블은 더 이상 소진되지 않습니다. 다음은 아직 열려 있습니다. - 타임아웃 없이 기다리는 태스크는 상대가 움직이지 않으면 영원히 기다릴 수 있습니다. 타임아웃은 호출마다 선택하는 기능이므로, 응답성을 유지해야 하는 서버나 루트 태스크는 모든 대기에 타임아웃을 지정해야 합니다. - - 타임아웃은 태스크가 언제 준비 상태가 되는지를 정할 뿐, 언제 실행되는지는 정하지 않습니다. 우선순위와 CPU 예산이 없습니다. 스케줄러는 1틱 슬라이스의 라운드 로빈이며, `Untyped` 메모리를 가진 태스크는 태스크를 많이 만들어 다른 모든 태스크의 몫을 희석시킬 수 있습니다. + - 타임아웃은 태스크가 언제 준비 상태가 되는지를 정할 뿐, 언제 실행되는지는 정하지 않습니다. 우선순위와 CPU 예산이 없으며, CPU를 많이 쓰는 태스크는 자기 차례를 모두 쓰고 이를 막는 것은 없습니다. 스케줄러는 틱이 1초인 라운드 로빈입니다. `Untyped` 메모리를 가진 태스크는 태스크를 많이 만들어 다른 모든 태스크의 몫을 희석시킬 수 있습니다. 준비된 태스크가 N개일 때 아래의 하한은 1/N이고, 태스크를 만들 때마다 N이 커지기 때문입니다. + - 틱 직전에 양보하거나 블록해서 다음 태스크의 CPU를 빼앗는 문제는 `main`에서 대응했습니다. `YIELD`는 케이퍼빌리티가 필요 없고, 이 변경 전에는 다음 태스크가 그 주기의 나머지만 받은 반면 양보한 태스크는 다음 주기 전체에서 큐의 맨 앞으로 돌아왔습니다(QEMU에서 CPU를 쓰는 태스크 둘일 때 상대 태스크의 몫이 약 52 %에서 8 %~11 %로, 커널이 카운터로 시간을 재면 3.5 %로 떨어졌습니다). 지금의 규칙은 다음과 같습니다. 두 틱 사이에 CPU를 받은 태스크(이전 태스크가 양보했거나, 블록했거나, 종료되었거나 강제 종료된 경우, 또는 커널이 유휴 상태에서 틱이 아닌 것 때문에 깨어난 경우)는 처음 만나는 틱에 선점되지 않습니다. 따라서 태스크는 한 주기를 온전히 실행하기 전에는 잘리지 않으며, 양보하거나 블록하지 않는 태스크는 준비된 태스크가 N개일 때 CPU의 1/N 이상을 가집니다. 이 하한은 스케줄러 모델에 대한 탐색(최대 6개 태스크)과 호스트 테스트(`crates/k0-slice`)로 확인했고 QEMU에서도 관찰했습니다(공격자가 주기의 90 %에서 양보할 때 상대 태스크는 53.8 %~54.9 %를 가졌습니다). 증명이 아니며 예산도 아닙니다. 부팅할 때마다 실행하는 자체 테스트(`root: slice test yield pass`, `root: slice test block pass`)가 이런 태스크가 첫 틱에서 끊기지 않는지를 양보 경로와 블록 경로에서 확인합니다. + - 스케줄러를 통한 타이밍 채널은 열려 있습니다. 태스크는 양보하거나 블록하는 시점을 골라 다른 태스크가 언제, 그리고 이제는 얼마나 오래 실행되는지를 여전히 바꿀 수 있습니다. 이것은 분석하지 않았으며, 닫으려면 고정 시간 분할이 필요한데 K0에는 없습니다. + - 실시간이나 지연 시간에 대한 약속은 없습니다. 커널은 선점되지 않고 틱은 1초입니다. 자기보다 먼저 실행될 태스크가 k개(실행 중인 태스크 포함)일 때 준비된 태스크는 이제 k + 1 틱 주기 안에 시작하며, 전에는 k 주기 안에 시작했으므로 대기가 최대 한 틱 길어질 수 있습니다. CPU를 쓰는 태스크 하나 뒤에서 호출과 응답을 주고받는 호출자와 서버는 모델에서 왕복당 2틱이 걸렸고 이제는 4틱이 걸립니다. 한 번에 한 주기에서 두 주기를 실행한다는 것과 k + 1 주기를 기다린다는 수치는 이 버전의 스케줄러를 설명할 뿐 인터페이스가 아닙니다. + - 규칙을 스케줄러에 연결하는 과정의 일부 실수는 실제 커널에 대한 어떤 테스트로도 발견되지 않습니다. 틱 자신의 전환이 잘못된 진입 종류를 넘기는 경우, 유휴 루프가 틱에 대해 잘못 보고하는 경우, 루트 태스크로 넘기는 시점의 진입 종류입니다. 이것은 태스크의 몫이 아니라 잘리기 전까지 실행되는 시간에 영향을 줍니다. 호스트 모델은 이 경우들에 대한 규칙을 검증할 뿐 커널이 규칙을 쓰는 방식은 검증하지 않습니다. 부팅 테스트는 이전 규칙과, 양보 경로나 블록 경로의 잘못된 진입 종류는 잡아냅니다. + - 측정에 쓴 공격자는 루트 태스크가 잰 루프 횟수로 양보 시점을 미리 맞춰 준 공격자입니다. 공격자가 그 시점을 스스로 찾는 데 무엇이 필요한지는 측정하지 않았습니다. 모든 실행은 QEMU(TCG와 HVF)에서 했고 하드웨어에서는 실행하지 않았습니다. - 커널은 선점되지 않습니다. 긴 시스템 콜(예: 오브젝트가 많은 `Untyped`에 대한 `CAP_REVOKE`)은 다른 모든 태스크와 모든 타임아웃을 지연시킵니다. - `k0_arch::fatal`이나 커널 패닉은 여전히 기계를 멈추며, EL0에서 발생한 SError도 마찬가지입니다. - 부트 로그의 커널 부분이 폴트 및 종료 줄로 채워질 수 있습니다. @@ -211,7 +216,7 @@ $ grep -a 'k0: console drivers' <이미지 파일> 1. 직렬 회선은 그 회선에 닿을 수 있는 쪽만큼만 신뢰할 수 있습니다. 운영자는 키를 지울 수 있으며, 이는 설계상의 서비스 거부입니다. 2. 커널의 수신 코드는 EL1에서 실행됩니다. 작고 바이트를 해석하지 않지만, 외부 당사자가 구동하는 커널 코드입니다. 사용자 공간 드라이버에는 장치와 인터럽트의 위임이 필요한데, K0에는 이것이 없습니다. 3. 외부 당사자가 이제 태스크 실행 중에 인터럽트를 일으킬 수 있으며, 그 빈도는 읽는 쪽이 제한합니다. 읽는 쪽은 틱보다 정밀한 도착 시각을 알게 되고, 다른 태스크는 빼앗긴 시간을 알아챌 수 있습니다. 이것은 분석하지 않은 타이밍 채널입니다. -4. 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 지연은 준비된 태스크마다 최대 한 틱입니다. +4. 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 지연은 준비된 태스크마다 최대 한 틱이고, 실행 중인 태스크가 두 틱 사이에 CPU를 받았다면 한 틱이 더 붙습니다. 5. 16550 콘솔에는 입력이 없습니다. SBSA UART 경로, FIFO 오버런, 수신 타임아웃 인터럽트는 QEMU에서 실행되지 않으며, 가짜 UART를 쓰는 호스트 테스트(`crates/k0-conin`)가 유일한 검증입니다. UART 원인 없이 발생하는 인터럽트 회선을 끊는 동작도 호스트 테스트로만 검증합니다. 6. 기계에서 폭주 중의 커널 시간을 측정한 테스트는 없습니다. 상한은 게이트에서 논증하고 호스트 테스트로 보입니다. 7. "프롬프트 전에 버림"은 UART에 닿은 바이트를 센 것입니다. 바이트를 붙잡아 두는 에뮬레이터나 어댑터는 나중에 전달하며, QEMU가 그렇게 합니다. diff --git a/USAGE.md b/USAGE.md index 87135b6..e544319 100644 --- a/USAGE.md +++ b/USAGE.md @@ -90,6 +90,8 @@ The following table lists the lines that an image with a console driver prints, | `k0: kernel reserve tables + address space entries = bytes in ranges` | The kernel set aside memory at the top of each range it hands out, for its own page tables and for the list of address spaces. It is printed before the `k0: untyped` lines. On QEMU virt with 512 MiB it reads `262 tables + 130130 address space entries = 0x206000 bytes in 3 ranges`. The entry count depends on the image size | | `k0: memory + not handed out ()` | A memory range was too small to hold its own share of that reserve, or the share could not be mapped, so the kernel did not hand the range out. The boot continues. A normal run on QEMU virt does not print it | | `root: timeout tests pass` | The self-tests of IPC timeouts passed | +| `root: slice test yield pass` and `root: slice test block pass` | A task that got the CPU between two ticks (by `YIELD`, or after the previous task blocked) was not cut by the first tick it met. They come before `root: preempt test pass` | +| `root: preempt test pass` | A task that never yields is still cut by the timer | | `root: kernel reserve tests pass` | The self-tests of the kernel reserve passed (300 address spaces alive at once, and frames made from untyped memory across many page table blocks) | | `root: oracle tests pass` | The self-tests of the signing oracle passed. Only an image built with a `vault` feature prints it (see "Signing oracle" below) | | `root: oracle made no key (boot seed has no entropy)` | The vault refused to make a key because the boot seed was too weak. Only an image built with a `vault` feature can print it, and then `root: oracle tests pass` does not follow | @@ -286,7 +288,7 @@ 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. +- **Latency**: input waits behind running tasks. There are no priorities, so the latency is up to a tick per ready task, plus one more tick when the running task was switched in between two ticks. - **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). @@ -407,8 +409,8 @@ $ 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 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/host-test.sh` runs the 363 host tests (277 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 363 are 15 (`k0-abi`), 44 (`k0-cap`), 85 (`k0-boot`), 33 (`k0-efi`), 15 (`k0-conin`), 9 (`k0-slice`, the rule that decides whether a tick cuts the running task, run on a model of the scheduler), 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 time slice test adds two runs of about 4 seconds in total where the preemption test it replaced took about 1. 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 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. diff --git a/USAGE_KR.md b/USAGE_KR.md index ccae298..8f86415 100644 --- a/USAGE_KR.md +++ b/USAGE_KR.md @@ -90,6 +90,8 @@ $ grep -a 'k0: console drivers' <이미지 파일> | `k0: kernel reserve tables + address space entries = bytes in ranges` | 커널이 넘겨 주는 메모리 범위마다 맨 위에 자기 페이지 테이블과 주소 공간 목록용 메모리를 따로 떼어 둠. `k0: untyped` 줄보다 먼저 출력됨. QEMU virt 512 MiB에서는 `262 tables + 130130 address space entries = 0x206000 bytes in 3 ranges`로 나오며, 항목 수는 이미지 크기에 따라 달라짐 | | `k0: memory + not handed out ()` | 메모리 범위가 너무 작아 그 예비 몫을 담지 못하거나 몫을 매핑하지 못해서, 커널이 그 범위를 넘겨 주지 않음. 부팅은 계속됨. QEMU virt의 정상 실행에서는 나오지 않음 | | `root: timeout tests pass` | IPC 타임아웃 자가 테스트가 통과함 | +| `root: slice test yield pass`, `root: slice test block pass` | 두 틱 사이에 CPU를 받은 태스크(`YIELD` 또는 앞선 태스크가 기다림)가 처음 만난 틱에 끊기지 않았음. `root: preempt test pass`보다 앞에 나옴 | +| `root: preempt test pass` | 양보하지 않는 태스크는 여전히 타이머가 끊음 | | `root: kernel reserve tests pass` | 커널 예비 공간 자가 테스트가 통과함(주소 공간 300개를 동시에 유지, 여러 페이지 테이블 블록에 걸친 untyped 메모리에서 프레임 생성) | | `root: oracle tests pass` | 서명 오라클 자가 테스트가 통과함. `vault` feature를 포함해 빌드한 이미지만 출력함(뒤의 "서명 오라클" 참고) | | `root: oracle made no key (boot seed has no entropy)` | 부트 시드가 약해서 볼트가 키 생성을 거부함. `vault` feature를 포함해 빌드한 이미지만 출력할 수 있으며, 이때 `root: oracle tests pass`는 뒤따르지 않음 | @@ -286,7 +288,7 @@ k0> - **커널 코드**: 수신 코드는 EL1에서 실행됩니다. 작고 바이트를 해석하지 않지만, 외부 당사자가 구동하는 커널 코드입니다. 사용자 공간 드라이버에는 장치 및 인터럽트 위임이 필요한데, K0에는 그것이 없습니다. - **타이밍**: 외부 당사자가 이제 태스크가 도는 동안 인터럽트를 일으킬 수 있고(읽는 쪽이 상한을 정함), 읽는 쪽은 틱보다 정밀한 도착 시각을 알게 됩니다. 다른 태스크가 빼앗긴 시간을 알아챌 수 있습니다. 이 타이밍 채널은 분석하지 않았습니다. -- **지연**: 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 지연은 준비된 태스크마다 최대 한 틱입니다. +- **지연**: 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 지연은 준비된 태스크마다 최대 한 틱이며, 실행 중인 태스크가 두 틱 사이에 실행을 넘겨받았다면 한 틱이 더해집니다. - **하드웨어**: 16550 콘솔에는 입력이 없습니다. SBSA UART 경로, FIFO 오버런, 수신 타임아웃 인터럽트는 QEMU로 실행되지 않고 가짜 UART를 쓰는 호스트 테스트로만 다룹니다. UART 원인 없이 발생하는 인터럽트 선을 끊는 동작도 호스트 테스트로만 다룹니다. 플러드 상황에서 커널이 쓰는 시간을 머신에서 측정하는 테스트는 없습니다. 실제 하드웨어에서는 아무것도 돌려 보지 않았습니다. - **화면**: 입력 중에 커널 줄이 나타나면 화면의 줄은 갈라지지만 버퍼는 온전하며, Enter는 버퍼 전체를 실행합니다. `Console` 출력이 있는 태스크는 여전히 커널이나 루트 태스크 줄처럼 보이는 줄을 출력할 수 있고, 접두어를 인증하는 것은 없습니다. 터미널은 추가로 자기 현재 줄 안을 지울 수 있습니다. - **붙잡힌 바이트**: "프롬프트 전에 버림"은 UART에 도착한 바이트를 말합니다. 바이트를 붙잡아 두는 에뮬레이터나 어댑터는 나중에 전달합니다(QEMU가 그렇습니다). @@ -407,8 +409,8 @@ $ tools/qemu-boot-test.sh # QEMU에서 부팅하 $ tools/boot-matrix.sh # 지원하는 구성을 전부 부팅(16 KiB 이미지, 고정 이미지, UEFI 로더 이미지도 빌드함) ``` -- `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/host-test.sh`는 호스트 테스트 363개를 실행합니다(그 밖의 호스트에서는 277개). 커널의 부분 하나하나를 내 컴퓨터에서 일반 프로그램처럼 돌리는 작은 테스트(단위 테스트)입니다. **퍼징**도 합니다. 디바이스 트리 파서와 UEFI 로더의 계획 코드에 무작위로 망가뜨린 입력을 넣어 충돌을 찾는 방법입니다. 363개는 `k0-abi` 15개, `k0-cap` 44개, `k0-boot` 85개, `k0-efi` 33개, `k0-conin` 15개, `k0-slice` 9개(틱이 실행 중인 태스크를 끊을지 정하는 규칙을 스케줄러 모델로 검사), `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초 더 걸립니다. 시간 조각 테스트는 두 번 실행해 합계 약 4초가 걸리며, 이를 대신한 이전 선점 테스트는 약 1초가 걸렸습니다. `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에서 76행, CI에서 65행입니다. 행 이름을 인자로 주면 그 행만 돌립니다. CI가 이것을 실행합니다. 콘솔 행은 콘솔 feature를 확인합니다. 다음 표는 콘솔 행과 확인하는 내용입니다. diff --git a/assets/scheduling-states.svg b/assets/scheduling-states.svg index eabf54d..808496d 100644 --- a/assets/scheduling-states.svg +++ b/assets/scheduling-states.svg @@ -39,7 +39,7 @@ - YIELD, timer preemption (rotate) + YIELD (rotate), timer (on_tick) BlockedSend BlockedRecv BlockedCall BlockedReply diff --git a/assets/scheduling-states_KR.svg b/assets/scheduling-states_KR.svg index bac1544..643134c 100644 --- a/assets/scheduling-states_KR.svg +++ b/assets/scheduling-states_KR.svg @@ -39,7 +39,7 @@ - YIELD, 타이머 선점 (rotate) + YIELD (rotate), 타이머 (on_tick) BlockedSend BlockedRecv BlockedCall BlockedReply diff --git a/ci/threat_model.md b/ci/threat_model.md index 767a6a4..e32828d 100644 --- a/ci/threat_model.md +++ b/ci/threat_model.md @@ -10,7 +10,7 @@ Trust boundaries, from least to most trusted: 1. **EL0 code via system calls (`svc`).** Every register a task passes to the kernel is attacker controlled: capability slot indices, virtual addresses, permission bits, sizes, object types, badges and message words. This is the primary attack surface. Entry path: `crates/k0-arch/src/vectors.S` (`__lower_common`) -> `crates/k0-arch/src/usermode.rs` (`el0_sync`) -> `kernel/src/syscall.rs` (`k0_syscall` and the `sys_*` functions). Slot arguments are resolved only in the calling task's own CNode. 2. **EL0 faults.** Data and instruction aborts, undefined instructions, trapped system register and FP/SIMD accesses, `brk` and alignment faults all reach `k0_fault` in `kernel/src/syscall.rs`, which must only kill the faulting task. -3. **Timer interrupts** taken at EL1 and from EL0 (`irq_current`, `irq_lower`), which drive preemption in `crates/k0-sched` and the expiry of IPC timeouts (`k0_ipc::expire_timeouts`, run on every tick, also from the idle loop). +3. **Timer interrupts** taken at EL1 and from EL0 (`irq_current`, `irq_lower`), which drive preemption in `crates/k0-sched` (the decision whether a tick cuts the running task is `crates/k0-slice`, called through `on_tick`) and the expiry of IPC timeouts (`k0_ipc::expire_timeouts`, run on every tick, also from the idle loop). 4. **The device tree blob (DTB)** that the boot chain passes in `x0`. Nothing reads it before the MMU is on. `kernel_main` in `kernel/src/main.rs` maps it read-only (`map_dtb`), then `crates/k0-boot/src/fdt.rs` reads the memory map and `crates/k0-boot/src/platform.rs` finds the console, the interrupt controller and the timer interrupt, both on the shared walker `crates/k0-boot/src/fdt/walk.rs`. The results become the physical memory map (`k0_cap::bootstrap`) and the device mappings, after `Platform::validate` has checked the devices against the memory map (`bring_up_platform` in `kernel/src/main.rs`). The boot chain is trusted to load an authentic kernel image, but the DTB code must still be total: no panic, no out-of-bounds read, no integer overflow on any input, and no device range that overlaps memory handed to user space. 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. @@ -53,7 +53,7 @@ Lower value: - 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`, `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. +- Host tests: `tools/host-test.sh` runs the unit tests of `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`, `k0-conin`, `k0-slice`, `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. @@ -83,14 +83,15 @@ These are known, tracked in `SECURITY.md`, and are not new findings: - No isolation between tasks in `v0.1.0` and earlier commits: one static root CNode, one address space, no capability derivation tree, no `MINT`, no `revoke`, no capability transfer over IPC (GHSA-vmpv-qc49-3p6r). Findings that only apply to those versions are not new. The current `main` branch (unreleased) has per-task CNodes and address spaces, rights, badges, a derivation list and revocation, so isolation bypasses there ARE in scope. EL0 reaching EL1 memory is always in scope. - Known limits of isolation on `main`: no fault delivery to a handler, no notifications, no capability transfer over IPC, a single core, and a sender already queued on an endpoint still delivers once after its capability is revoked. Availability is not protected in general (see below). New executable code cannot be loaded after boot by design, so a confined task runs code from the root task image. -- Availability limits (GHSA-q99x-2wrv-358p is still listed as affecting 0.1.0 and earlier, with no fixed version; `main` contains a change that addresses its subject). The kernel no longer halts when every task is blocked: it idles and prints `k0: idle (waiting for a timeout)` or `k0: all tasks stopped (none ready, no timeout pending)` once. A task can bound its own waits with the timeout in the upper 32 bits of `x1` (scheduler ticks of 1 second; `TIMEOUT`, `REPLY_TIMEOUT`, `BAD_FLAGS`). Still known: a wait without a timeout can last forever if the partner never acts; a timeout says when a task becomes ready, not when it runs (round-robin, one-tick slice, no priority or CPU budget, so a task with `Untyped` memory can dilute everybody's share by creating tasks); the kernel is not preemptible, so a long system call such as `CAP_REVOKE` on an `Untyped` with many objects delays every task and every timeout; `k0_arch::fatal`, a kernel panic and an SError from EL0 stop the machine; fault and exit lines can fill the kernel part of the boot log. +- Availability limits (GHSA-q99x-2wrv-358p is still listed as affecting 0.1.0 and earlier, with no fixed version; `main` contains a change that addresses its subject). The kernel no longer halts when every task is blocked: it idles and prints `k0: idle (waiting for a timeout)` or `k0: all tasks stopped (none ready, no timeout pending)` once. A task can bound its own waits with the timeout in the upper 32 bits of `x1` (scheduler ticks of 1 second; `TIMEOUT`, `REPLY_TIMEOUT`, `BAD_FLAGS`). Still known: a wait without a timeout can last forever if the partner never acts; a timeout says when a task becomes ready, not when it runs (round-robin with a tick of one second, no priority or CPU budget, so a task with `Untyped` memory can dilute everybody's share by creating tasks, which stays known); the kernel is not preemptible, so a long system call such as `CAP_REVOKE` on an `Untyped` with many objects delays every task and every timeout; `k0_arch::fatal`, a kernel panic and an SError from EL0 stop the machine; fault and exit lines can fill the kernel part of the boot log. +- Scheduler timing, addressed on `main`: taking the CPU from the next task by calling `YIELD` (no capability needed) or blocking just before the tick. A task that gets the CPU between two ticks is no longer preempted by the first tick it meets (`crates/k0-slice`, used by `on_tick` and `resume_from_idle` in `crates/k0-sched`), so it is not cut before it has run one full period, and with N ready tasks a task that never yields or blocks keeps at least 1/N of the CPU. This was checked by search in a model (up to 6 tasks) and by host tests, not proven, and a self-test at every boot (`root: slice test yield pass`, `root: slice test block pass`) covers the kernel's use of it. A report that breaks this is still welcome. Known limits that stay: the share has no budget and N grows with every task created; the timing channel through the scheduler is open (a task changes when, and for how long, another task runs by choosing when to yield or block, and this has not been analysed); there is no latency promise (a task that becomes ready can wait up to one tick longer than before); three connections of the rule to the scheduler (the tick's own switch, the idle loop's report of a tick, the entry kind at the hand-off to the root task) are covered only by the host model and by no test on the real kernel, so a report that one of them is wrong is still welcome, as a latency finding; the measurements ran in QEMU only, with an attacker whose yield point was set for it. - EL0 still cannot read a hardware counter or timer. Timeouts give it a clock as coarse as the scheduler tick; whether that can be amplified into a timing source for cache or speculation attacks has not been analysed. - The kernel tables are sized at boot: alias page tables and address space entries are reserved from the top of every range handed out as `Untyped` (`k0: kernel reserve ...` line), so `RETYPE` no longer fails with `KERNEL_RESOURCE` for lack of tables and the number of address spaces is limited only by memory. The 40-table static pool is used only during boot. - 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, 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. +- 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, plus one more when the running task got the CPU between two ticks); 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 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`. diff --git a/crates/k0-sched/Cargo.toml b/crates/k0-sched/Cargo.toml index 27ad011..46f0bbf 100644 --- a/crates/k0-sched/Cargo.toml +++ b/crates/k0-sched/Cargo.toml @@ -16,3 +16,4 @@ granule-16k = ["k0-task/granule-16k", "k0-mm/granule-16k"] k0-arch = { path = "../k0-arch" } k0-mm = { path = "../k0-mm", default-features = false } k0-task = { path = "../k0-task", default-features = false } +k0-slice = { path = "../k0-slice" } diff --git a/crates/k0-sched/src/lib.rs b/crates/k0-sched/src/lib.rs index 2a0e97f..7276244 100644 --- a/crates/k0-sched/src/lib.rs +++ b/crates/k0-sched/src/lib.rs @@ -7,9 +7,19 @@ //! 컨텍스트에서만 실행되고, 벡터가 사용자 컨텍스트를 현재 TCB에 저장한 //! 상태에서 전환이 일어나므로 전환은 `__current_context` 포인터 갱신과 //! TTBR0 교체(주소 공간이 다를 때만, ASID 미사용이라 전체 TLB 무효화 -//! 동반)로 끝납니다. 선점 신호는 진입 페이즈 2의 타이머 틱입니다. -//! IPC 블록은 [block_and_switch]로 현재 태스크를 준비 큐 밖(엔드포인트 -//! 대기 큐나 reply 링크)에서 재우고, 깨우기는 [enqueue]입니다. +//! 동반)로 끝납니다. IPC 블록은 [block_and_switch]로 현재 태스크를 준비 큐 +//! 밖(엔드포인트 대기 큐나 reply 링크)에서 재우고, 깨우기는 [enqueue]입니다. +//! +//! 선점 신호는 타이머 틱이고 판정은 [on_tick]이 합니다. 타이머는 전환할 때 +//! 다시 걸지 않으므로, 틱이 실행 중인 태스크를 무조건 끊으면 틱 직전에 양보한 +//! 태스크가 뒤에 선 태스크에게 주기의 끝자락만 주고 다음 주기를 통째로 다시 +//! 받습니다. 그래서 틱과 틱 사이에 CPU를 받은 태스크는 처음 맞는 틱 하나를 +//! 넘깁니다. 틱의 판정으로 CPU를 받은 태스크는 주기의 처음에 들어온 것이라 +//! 다음 틱에서 끊깁니다. 어느 쪽이든 CPU를 받은 태스크는 스스로 내놓지 않는 +//! 한 온전한 한 주기 전에는 끊기지 않습니다. 규칙 자체는 k0-slice 크레이트에 +//! 있고 호스트에서 시험합니다. 여기서는 현재 태스크가 바뀌는 유일한 자리인 +//! `switch_to`가 들어온 경위를 규칙에 알려 줍니다. 깨어나는 것만으로는 면제가 +//! 생기지 않습니다(깨어난 태스크는 준비 큐의 끝에 설 뿐임). //! //! 기한이 있는 IPC 대기자는 준비 큐나 대기 큐와 별개인 기한 목록에도 //! 들어갑니다([arm_timeout]). 블록된 태스크가 블록 상태를 벗어나는 길은 @@ -30,6 +40,7 @@ use core::cell::UnsafeCell; +use k0_slice::{Entry, Slice, Verdict}; use k0_task::{TaskState, Tcb, TcbQueue}; /// 스케줄러 상태 구조체입니다. `current`는 TCB의 커널 VA(0 = 없음)입니다. @@ -42,6 +53,9 @@ struct Sched { /// 않으므로 실제보다 이를 수 있고(그러면 한 번 헛되이 훑을 뿐), 늦을 수는 /// 없음 timed_min: u64, + /// 현재 태스크가 다음 틱 하나를 넘길 수 있는지. `current`를 바꾸는 자리 + /// (handoff와 switch_to)에서만 다시 정하고 [on_tick]만 씀 + slice: Slice, } struct SyncCell(UnsafeCell); @@ -56,6 +70,7 @@ static SCHED: SyncCell = SyncCell(UnsafeCell::new(Sched { ready: TcbQueue::new(), timed: 0, timed_min: 0, + slice: Slice::new(), })); /// 준비 큐 꼬리에 TCB를 붙이는 함수입니다. @@ -84,10 +99,18 @@ unsafe fn pop(s: &mut Sched) -> u64 { /// 벡터의 복귀 경로(`__user_restore`)가 `__current_context`를 다시 읽기 /// 때문에 포인터 갱신만으로 전환이 완성됩니다. /// +/// 현재 태스크가 바뀌는 자리는 이 함수와 handoff뿐이므로 틱 면제도 여기서 +/// 정합니다. 경위를 인자로 반드시 받으며, 앞 태스크가 남긴 값은 버립니다. +/// +/// # Arguments +/// `next` - 준비 큐에서 꺼낸 TCB의 커널 VA +/// `how` - 그 태스크가 CPU를 받는 경위(틱의 판정인지, 틱 사이의 전환인지) +/// /// # Safety /// `next`는 준비 큐에서 나온 유효한 TCB여야 하고, 현재 태스크의 컨텍스트 /// 저장이 끝난 예외 컨텍스트여야 합니다(벡터가 보장). -unsafe fn switch_to(s: &mut Sched, next: u64) { +unsafe fn switch_to(s: &mut Sched, next: u64, how: Entry) { + s.slice.entered(how); let t = next as *mut Tcb; // SAFETY: 함수 계약대로 t는 유효한 TCB임 unsafe { @@ -251,6 +274,8 @@ pub unsafe fn handoff(tcb: &'static mut Tcb) -> ! { // SAFETY: 이양 직전의 단일 부트 코어라 접근이 배타적임 let s = unsafe { &mut *SCHED.0.get() }; s.current = core::ptr::from_mut(tcb) as u64; + // 부팅 중에도 타이머는 돌고 있어서 루트 태스크는 주기의 중간에 들어옴 + s.slice.entered(Entry::Between); k0_arch::usermode::set_current(&raw mut tcb.ctx); // SAFETY: 함수 계약대로 컨텍스트와 주소 공간이 준비된 발산 경로에서 호출됨 unsafe { k0_arch::usermode::enter_user() } @@ -279,28 +304,72 @@ pub unsafe fn enqueue(tcb: *mut Tcb) { } } -/// 현재 태스크를 큐 꼬리로 돌리고 다음 태스크를 실행하는 함수입니다. +/// 현재 태스크를 큐 꼬리로 돌리고 준비 큐의 머리를 실행하는 함수입니다. +/// 준비된 다른 태스크가 없으면 아무 일도 하지 않고 false를 줍니다. /// -/// 라운드 로빈 전환점이며 YIELD와 타이머 선점이 공유합니다. 준비된 다른 -/// 태스크가 없으면 아무 일도 하지 않고 현재 태스크가 계속됩니다. +/// # Arguments +/// `how` - 머리의 태스크가 CPU를 받는 경위 /// /// # Safety /// 시스템 콜/IRQ 컨텍스트에서 벡터의 컨텍스트 저장이 끝난 뒤에만 호출해야 -/// 합니다. -pub unsafe fn rotate() { - // SAFETY: 함수 계약대로 접근이 배타적임 - let s = unsafe { &mut *SCHED.0.get() }; +/// 하고, 현재 태스크는 실행 중(Running)이어야 합니다. +unsafe fn rotate_as(s: &mut Sched, how: Entry) -> bool { // SAFETY: 큐 링크는 이 모듈만 만지므로 유효함 let next = unsafe { pop(s) }; if next == 0 { - return; + return false; } let cur = s.current; // SAFETY: current는 handoff/switch_to가 유지하는 유효한 TCB이고 next는 // 방금 큐에서 나옴 unsafe { push(s, cur as *mut Tcb); - switch_to(s, next); + switch_to(s, next, how); + } + true +} + +/// 현재 태스크가 CPU를 내놓는 함수입니다(YIELD). +/// +/// 현재 태스크를 큐 꼬리로 돌리고 다음 태스크를 실행합니다. 준비된 다른 +/// 태스크가 없으면 아무 일도 하지 않고 현재 태스크가 계속되며, 그때는 틱 +/// 면제도 생기거나 사라지지 않습니다. 넘겨받은 태스크는 주기의 중간에 +/// 들어오므로 처음 맞는 틱 하나를 넘깁니다. +/// +/// # Safety +/// 시스템 콜 컨텍스트에서 벡터의 컨텍스트 저장이 끝난 뒤에만 호출해야 +/// 합니다. +pub unsafe fn rotate() { + // SAFETY: 함수 계약대로 접근이 배타적이고 계약을 rotate_as로 중계함 + unsafe { + let _ = rotate_as(&mut *SCHED.0.get(), Entry::Between); + } +} + +/// 실행 중인 태스크를 끊고 들어온 타이머 틱을 판정하는 함수입니다. +/// +/// 현재 태스크가 틱 사이에 CPU를 받았고 그 뒤로 틱을 맞은 적이 없으면 이번 +/// 틱은 그 면제를 쓰는 것으로 끝나고 현재 태스크가 계속됩니다. 그렇지 않으면 +/// 현재 태스크를 큐 꼬리로 돌리고 다음 태스크를 실행합니다(준비된 태스크가 +/// 없으면 그대로 계속). 틱에서 CPU를 받은 태스크는 주기의 처음에 들어온 +/// 것이므로 면제가 없습니다. +/// +/// 틱마다 정확히 한 번, 기한이 지난 대기자를 깨운 뒤에 불러야 합니다. 커널이 +/// 실행할 태스크 없이 기다리는 동안의 틱에는 부르지 않습니다(그때는 끊을 +/// 태스크가 없고, 깨어난 태스크는 [resume_from_idle]이 들여보냄). +/// +/// # Safety +/// EL0에서 진입한 IRQ의 핸들러에서 벡터의 컨텍스트 저장이 끝난 뒤에만 +/// 호출해야 합니다(현재 태스크가 실행 중이던 문맥). +pub unsafe fn on_tick() { + // SAFETY: 함수 계약대로 접근이 배타적임 + let s = unsafe { &mut *SCHED.0.get() }; + if s.slice.on_tick() == Verdict::Keep { + return; + } + // SAFETY: 함수 계약을 rotate_as로 중계함 + unsafe { + let _ = rotate_as(s, Entry::Tick); } } @@ -314,32 +383,68 @@ pub unsafe fn current() -> *mut Tcb { s.current as *mut Tcb } -/// 블록 표시를 마친 현재 태스크를 두고 다음 태스크로 전환하는 함수입니다. +/// 현재 태스크를 준비 큐에 되돌리지 않고 준비 큐의 머리로 전환하는 +/// 함수입니다. 준비된 태스크가 없으면 false를 줍니다. +/// +/// # Arguments +/// `how` - 머리의 태스크가 CPU를 받는 경위 +/// +/// # Safety +/// [rotate]와 동일합니다. +unsafe fn switch_next(s: &mut Sched, how: Entry) -> bool { + // SAFETY: 큐 링크는 유효함 + let next = unsafe { pop(s) }; + if next == 0 { + return false; + } + // SAFETY: next는 방금 큐에서 나온 유효한 TCB임 + unsafe { switch_to(s, next, how) }; + true +} + +/// 블록 표시를 마친(또는 종료된) 현재 태스크를 두고 다음 태스크로 전환하는 +/// 함수입니다. /// /// 현재 태스크를 준비 큐에 되돌리지 않는 것이 [rotate]와의 차이입니다. /// 호출 전에 현재 태스크를 깨울 주체(엔드포인트 대기 큐나 수신자의 reply /// 링크)에 걸어 두어야 유실되지 않습니다. /// +/// 넘겨받은 태스크는 주기의 중간에 들어오므로 처음 맞는 틱 하나를 넘깁니다. +/// 양보뿐 아니라 블록과 종료도 면제를 주어야, 틱 직전에 블록하는 것으로 뒤에 +/// 선 태스크의 몫을 줄이는 길이 막힙니다. +/// +/// # Errors +/// 준비된 태스크가 없으면 false를 반환합니다. 호출자는 인터럽트를 기다렸다가 +/// [resume_from_idle]을 불러야 합니다 +/// +/// # Safety +/// [rotate]와 동일합니다. +pub unsafe fn block_and_switch() -> bool { + // SAFETY: 함수 계약대로 접근이 배타적이고 계약을 switch_next로 중계함 + unsafe { switch_next(&mut *SCHED.0.get(), Entry::Between) } +} + +/// 실행할 태스크 없이 기다리던 커널이 준비된 태스크로 전환하는 함수입니다. +/// /// 블록된 채로 기다리던 현재 태스크 자신이 준비 큐에 돌아와 있으면 그 /// 태스크로 전환합니다(같은 컨텍스트로 복귀). /// +/// 기다리는 동안 틱이 지나갔으면 그 태스크는 틱 처리 직후, 곧 주기의 처음에 +/// 들어오므로 틱 면제가 없습니다. 틱 없이 깨어났으면(콘솔 입력) 주기의 중간에 +/// 들어오는 것이라 면제를 받습니다. +/// +/// # Arguments +/// `tick_seen` - 마지막으로 전환을 시도한 뒤로 틱이 지나갔는지 +/// /// # Errors /// 준비된 태스크가 없으면 false를 반환합니다. 호출자는 다음 인터럽트를 /// 기다렸다가 다시 불러야 합니다 /// /// # Safety /// [rotate]와 동일합니다. -pub unsafe fn block_and_switch() -> bool { - // SAFETY: 함수 계약대로 접근이 배타적임 - let s = unsafe { &mut *SCHED.0.get() }; - // SAFETY: 큐 링크는 유효함 - let next = unsafe { pop(s) }; - if next == 0 { - return false; - } - // SAFETY: next는 방금 큐에서 나온 유효한 TCB임 - unsafe { switch_to(s, next) }; - true +pub unsafe fn resume_from_idle(tick_seen: bool) -> bool { + // SAFETY: 함수 계약대로 접근이 배타적이고 계약을 switch_next로 중계함 + unsafe { switch_next(&mut *SCHED.0.get(), Entry::after_idle(tick_seen)) } } /// 준비 큐에 있는 TCB를 큐에서 빼내는 함수입니다. diff --git a/crates/k0-slice/Cargo.toml b/crates/k0-slice/Cargo.toml new file mode 100644 index 0000000..bffe302 --- /dev/null +++ b/crates/k0-slice/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "k0-slice" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] diff --git a/crates/k0-slice/src/lib.rs b/crates/k0-slice/src/lib.rs new file mode 100644 index 0000000..ed5300f --- /dev/null +++ b/crates/k0-slice/src/lib.rs @@ -0,0 +1,124 @@ +//! 타이머 틱이 현재 태스크를 끊을지 정하는 규칙을 담는 크레이트입니다. +//! +//! # Features +//! 준비 큐와 문맥 전환은 k0-sched에 있고, 이 크레이트는 판정 하나만 합니다. +//! "지금 온 틱이 현재 태스크를 끊는가"입니다. 하드웨어에도 스케줄러 상태에도 +//! 닿지 않으므로 호스트 테스트가 가짜 준비 큐 위에서 같은 코드를 돌립니다. +//! +//! 규칙은 다음과 같습니다. +//! +//! - 틱의 판정으로 CPU를 받은 태스크([Entry::Tick])는 주기의 처음에 들어온 +//! 것이므로 다음 틱에서 끊깁니다. +//! - 틱과 틱 사이에 CPU를 받은 태스크([Entry::Between])는 처음 맞는 틱 하나를 +//! 넘깁니다. 앞선 태스크가 양보했거나, 블록됐거나, 종료됐거나, 커널이 대기 +//! 중에 틱이 아닌 일로 깨어난 경우입니다. 그 태스크는 주기의 남은 조각만 +//! 받고 들어왔으므로, 넘긴 틱부터 온전한 한 주기를 채운 뒤에 끊깁니다. +//! +//! 이 규칙이 없으면 틱 직전에 양보하는 태스크가 뒤에 선 태스크에게 주기의 +//! 끝자락만 주고 다음 주기를 통째로 다시 받습니다. 규칙이 지키는 것은 "CPU를 +//! 받은 태스크는 스스로 내놓지 않는 한 온전한 한 주기 전에는 끊기지 않는다" +//! 입니다. 그 결과 준비된 태스크가 N개일 때 계속 도는 태스크의 몫은 다른 +//! 태스크가 양보와 블록을 어떻게 섞어도 1/N 아래로 내려가지 않습니다(테스트가 +//! 무작위 일정과 격자 탐색으로 확인하며, 증명은 아님). +//! +//! 면제는 전환할 때마다 들어온 경위만으로 다시 정해집니다([Slice::entered]는 +//! 이전 값에 기대지 않고 대입함). 그래서 전환 경로 하나가 표시를 빠뜨려 앞 +//! 태스크의 면제가 다음 태스크에 남는 일이 없습니다. +//! +//! 막지 않는 것도 있습니다. 태스크는 양보하거나 블록하는 시점으로 다른 +//! 태스크가 언제 얼마나 도는지를 여전히 바꿀 수 있으므로, 스케줄러를 통한 +//! 타이밍 채널은 그대로입니다. +//! +//! # Examples +//! ```rust,ignore +//! let mut slice = Slice::new(); +//! slice.entered(Entry::Between); +//! assert_eq!(slice.on_tick(), Verdict::Keep); +//! assert_eq!(slice.on_tick(), Verdict::Rotate); +//! ``` + +#![cfg_attr(not(test), no_std)] +#![forbid(unsafe_code)] + +#[cfg(test)] +mod tests; + +/// 현재 태스크가 CPU를 받은 경위를 나타내는 열거형입니다. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Entry { + /// 틱의 판정으로 받음(주기의 처음) + Tick, + /// 틱과 틱 사이에 받음(양보, 블록, 종료, 틱이 아닌 일로 끝난 대기) + Between, +} + +impl Entry { + /// 커널이 실행할 태스크 없이 기다리다가 태스크를 들여보낼 때의 경위를 + /// 정하는 함수입니다. + /// + /// 기다리는 동안 틱이 지나갔으면 그 태스크는 틱 처리 직후에, 곧 주기의 + /// 처음에 들어오므로 면제가 없습니다. 틱 없이 깨어났으면(콘솔 입력) 주기 + /// 중간에 들어오는 것입니다. 둘이 함께 일어났으면 틱으로 봅니다. + /// + /// # Arguments + /// `tick_seen` - 기다리는 동안 틱이 한 번이라도 지나갔는지 + pub const fn after_idle(tick_seen: bool) -> Self { + if tick_seen { Self::Tick } else { Self::Between } + } +} + +/// 틱 하나에 대한 판정을 나타내는 열거형입니다. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Verdict { + /// 현재 태스크를 계속 실행함 + Keep, + /// 준비된 태스크가 있으면 현재 태스크를 준비 큐의 끝으로 돌림 + Rotate, +} + +/// 현재 태스크가 다음 틱 하나를 넘길 수 있는지를 담는 구조체입니다. +/// +/// 스케줄러가 현재 태스크를 가리키는 값 옆에 하나만 둡니다. 태스크마다 두지 +/// 않는 까닭은 이 값이 지금 실행 중인 태스크에 대해서만 뜻이 있기 때문입니다. +/// 값이 참이라는 것은 "현재 태스크가 틱의 판정이 아닌 전환으로 들어왔고 그 +/// 뒤로 틱을 맞은 적이 없다"는 뜻입니다. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Slice { + exempt: bool, +} + +impl Slice { + /// 면제가 없는 상태를 만드는 함수입니다. + pub const fn new() -> Self { + Self { exempt: false } + } + + /// 현재 태스크가 바뀔 때마다 부르는 함수입니다. + /// + /// 앞 태스크가 남긴 값은 버리고 경위만으로 면제를 정합니다. + /// + /// # Arguments + /// `how` - 새 현재 태스크가 CPU를 받은 경위 + pub fn entered(&mut self, how: Entry) { + self.exempt = matches!(how, Entry::Between); + } + + /// 현재 태스크가 실행 중일 때 온 틱 하나를 판정하는 함수입니다. + /// + /// 면제가 있으면 그것을 쓰고 [Verdict::Keep]을 줍니다. 면제는 한 번뿐이라 + /// 그다음 틱은 [Verdict::Rotate]입니다. + pub fn on_tick(&mut self) -> Verdict { + if self.exempt { + self.exempt = false; + Verdict::Keep + } else { + Verdict::Rotate + } + } +} + +impl Default for Slice { + fn default() -> Self { + Self::new() + } +} diff --git a/crates/k0-slice/src/tests.rs b/crates/k0-slice/src/tests.rs new file mode 100644 index 0000000..661e925 --- /dev/null +++ b/crates/k0-slice/src/tests.rs @@ -0,0 +1,634 @@ +//! 규칙을 가짜 준비 큐 위에서 검증하는 테스트 모듈입니다. +//! +//! 모형은 커널의 스케줄러가 하는 일을 한 주기가 100칸인 시간 위에서 흉내 +//! 냅니다. 준비 큐는 선입선출이고 깨어난 태스크는 큐의 끝에 섭니다. 틱은 먼저 +//! 기다리던 태스크를 깨운 다음에 현재 태스크를 판정합니다. 틱 n개짜리 기한 +//! 대기는 그때의 틱 수에 n + 1을 더한 틱에서 끝납니다. 양보는 준비된 태스크가 +//! 있을 때만 전환합니다. +//! +//! 규칙이 옳은지는 규칙과 따로 적은 기준으로 판정합니다. 모형은 전환이 틱의 +//! 판정에서 일어났는지 틱 사이에서 일어났는지를 스스로 알고 있으므로, 틱마다 +//! "틱 사이에 들어와 아직 틱을 맞지 않은 태스크만 넘어가고, 나머지는 준비된 +//! 태스크가 있으면 반드시 끊긴다"와 실제로 일어난 일을 비교합니다. 커널이 +//! 규칙에 경위를 잘못 알려 주는 경우([Wiring]의 나머지 값)도 같은 기준에 +//! 걸리는지 봅니다. 이 기준은 규칙을 다른 말로 다시 적은 것이라서, 결과로 +//! 나타나는 성질(끊긴 구간의 길이, 몫, 기다린 시간)을 따로 확인합니다. +//! +//! `Wiring::Kernel`은 커널의 연결을 손으로 옮겨 적은 것입니다(k0-sched의 +//! `rotate`, `on_tick`, `block_and_switch`, `resume_from_idle`, `handoff`와 +//! kernel의 `idle_until_ready`). 커널 쪽 연결이 바뀌어도 이 테스트는 실패하지 +//! 않으므로, 연결을 고칠 때는 여기도 함께 고쳐야 합니다. +//! +//! 모형이 다루지 않는 것은 다음과 같습니다. 태스크가 새로 만들어지는 경우, +//! 시스템 콜에 걸리는 시간, 긴 시스템 콜 때문에 늦어지거나 합쳐지는 틱, 그리고 +//! 실제 준비 큐의 구현입니다. + +use std::collections::VecDeque; + +use super::*; + +/// 한 주기의 길이(모형의 시간 단위) +const P: u64 = 100; + +/// 태스크가 정해진 시간만큼 돈 뒤에 하는 일입니다. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Op { + /// 양보도 블록도 하지 않고 끝없이 돎 + Spin, + Yield, + /// 틱 n개짜리 기한 대기 + Wait(u64), + /// 틱과 무관한 시각에 끝나는 대기(콘솔 입력). 값은 깨어나기까지의 시간 + Input(u64), + Exit, +} + +/// (도는 시간, 그 뒤에 하는 일)의 되풀이 +type Prog = Vec<(u64, Op)>; + +/// 커널이 규칙에 경위를 알려 주는 방식입니다. `Kernel`이 실제 연결이고 나머지는 +/// 일부러 틀리게 만든 것입니다. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Wiring { + Kernel, + /// 규칙이 없던 때: 틱은 언제나 현재 태스크를 끊음 + Old, + YieldAsTick, + BlockAsTick, + ExitAsTick, + TickAsBetween, + IdleTickAsBetween, + IdleInputAsTick, + BootAsTick, + /// 준비된 태스크가 없어 전환하지 않은 양보가 면제를 새로 줌 + YieldAloneMarks, +} + +/// 전환이 일어나는 자리입니다. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Path { + Tick, + Yield, + Block, + Exit, + /// 실행할 태스크 없이 기다리다가 틱에서 깨어남 + IdleTick, + /// 실행할 태스크 없이 기다리다가 틱이 아닌 시각의 입력으로 깨어남 + IdleInput, + /// 부팅 뒤 첫 태스크의 시작(주기의 중간) + Boot, +} + +impl Path { + /// 규칙과 따로 적은 기준: 이 자리에서 들어온 태스크가 주기의 처음에 + /// 들어온 것인지, 중간에 들어온 것인지 + fn truth(self) -> Entry { + match self { + Path::Tick | Path::IdleTick => Entry::Tick, + Path::Yield | Path::Block | Path::Exit | Path::IdleInput | Path::Boot => { + Entry::Between + } + } + } +} + +/// 모형이 시작하는 시각. 커널이 루트 태스크로 넘어가는 때처럼 주기의 중간임 +const START: u64 = P / 3; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum State { + Ready, + Running, + Blocked, + Dead, +} + +struct Task { + prog: Prog, + pc: usize, + left: u64, + state: State, + /// 기한 대기가 끝나는 틱 수(0 = 없음) + deadline: u64, + /// 입력 대기가 끝나는 시각(0 = 없음) + wake_at: u64, + cpu: u64, + /// 준비 큐에 선 시각과 그때 이 태스크보다 먼저 실행될 태스크의 수(큐에서 + /// 앞에 선 태스크와, 있다면 실행 중인 태스크) + queued: Option<(u64, u64)>, +} + +#[derive(Clone, Copy, Debug)] +struct Run { + task: usize, + truth: Entry, + start: u64, + ticks_seen: u64, +} + +struct Sim { + tasks: Vec, + queue: VecDeque, + run: Option, + slice: Slice, + now: u64, + ticks: u64, + wiring: Wiring, + /// 시스템 콜과 틱이 같은 시각에 걸렸을 때 틱을 먼저 처리하는지 + tick_first: bool, + /// 기준과 실제가 어긋난 틱의 수 + violations: u64, + /// 틱에 끊긴 실행 구간의 수와 그 가운데 가장 짧은 것 + cuts: u64, + shortest_cut: u64, + /// 준비 큐에서 기다린 시간에서 "먼저 실행될 태스크마다 한 주기"를 뺀 값 + /// 가운데 가장 큰 것 + worst_wait: i64, +} + +impl Sim { + /// 0번 태스크가 주기의 중간에서 실행을 시작하고 나머지는 번호 순서로 준비 + /// 큐에 선 상태를 만드는 함수입니다. + fn new(progs: Vec, wiring: Wiring) -> Self { + let tasks = progs + .into_iter() + .map(|prog| { + assert!(prog.iter().all(|&(run, _)| run >= 1), "every step must take time"); + Task { + left: prog[0].0, + prog, + pc: 0, + state: State::Ready, + deadline: 0, + wake_at: 0, + cpu: 0, + queued: None, + } + }) + .collect::>(); + let mut s = Self { + tasks, + queue: VecDeque::new(), + run: Some(Run { + task: 0, + truth: Path::Boot.truth(), + start: START, + ticks_seen: 0, + }), + slice: Slice::new(), + now: START, + ticks: 0, + wiring, + tick_first: false, + violations: 0, + cuts: 0, + shortest_cut: u64::MAX, + worst_wait: i64::MIN, + }; + s.tasks[0].state = State::Running; + s.slice.entered(s.told(Path::Boot)); + for t in 1..s.tasks.len() { + s.enqueue(t); + } + s + } + + fn enqueue(&mut self, t: usize) { + self.tasks[t].state = State::Ready; + let before = self.queue.len() as u64 + u64::from(self.run.is_some()); + self.tasks[t].queued = Some((self.now, before)); + self.queue.push_back(t); + } + + /// 이 연결이 규칙에 알려 주는 경위 + fn told(&self, path: Path) -> Entry { + let kernel = match path { + Path::Tick => Entry::Tick, + Path::Yield | Path::Block | Path::Exit | Path::Boot => Entry::Between, + Path::IdleTick => Entry::after_idle(true), + Path::IdleInput => Entry::after_idle(false), + }; + match (self.wiring, path) { + (Wiring::YieldAsTick, Path::Yield) + | (Wiring::BlockAsTick, Path::Block) + | (Wiring::ExitAsTick, Path::Exit) + | (Wiring::IdleInputAsTick, Path::IdleInput) + | (Wiring::BootAsTick, Path::Boot) => Entry::Tick, + (Wiring::TickAsBetween, Path::Tick) | (Wiring::IdleTickAsBetween, Path::IdleTick) => { + Entry::Between + } + _ => kernel, + } + } + + /// 준비 큐의 머리를 현재 태스크로 만드는 함수입니다. + fn switch_in(&mut self, path: Path) { + let t = self.queue.pop_front().expect("switch with an empty queue"); + let (t0, before) = self.tasks[t].queued.take().expect("ready task without a record"); + let over = (self.now - t0) as i64 - (before * P) as i64; + self.worst_wait = self.worst_wait.max(over); + self.tasks[t].state = State::Running; + self.slice.entered(self.told(path)); + self.run = Some(Run { + task: t, + truth: path.truth(), + start: self.now, + ticks_seen: 0, + }); + } + + fn tick(&mut self) { + self.ticks += 1; + // 커널의 틱 처리 순서: 입력을 기다리던 태스크, 기한이 지난 대기자, 판정 + for t in 0..self.tasks.len() { + let task = &mut self.tasks[t]; + if task.state == State::Blocked && task.wake_at != 0 && task.wake_at <= self.now { + task.wake_at = 0; + self.enqueue(t); + } + } + for t in 0..self.tasks.len() { + let task = &mut self.tasks[t]; + if task.state == State::Blocked && task.deadline != 0 && task.deadline <= self.ticks { + task.deadline = 0; + self.enqueue(t); + } + } + let Some(mut run) = self.run else { + if !self.queue.is_empty() { + self.switch_in(Path::IdleTick); + } + return; + }; + let verdict = if self.wiring == Wiring::Old { Verdict::Rotate } else { self.slice.on_tick() }; + let rotated = verdict == Verdict::Rotate && !self.queue.is_empty(); + let exempt = run.truth == Entry::Between && run.ticks_seen == 0; + if (exempt && rotated) || (!exempt && !self.queue.is_empty() && !rotated) { + self.violations += 1; + } + run.ticks_seen += 1; + self.run = Some(run); + if rotated { + self.cuts += 1; + self.shortest_cut = self.shortest_cut.min(self.now - run.start); + // 커널과 같은 순서: 머리를 꺼낸 뒤에 끊긴 태스크를 끝에 넣음 + self.switch_in(Path::Tick); + self.enqueue(run.task); + } + } + + /// 현재 태스크가 자기 차례의 일을 하는 함수입니다. + fn do_op(&mut self) { + let run = self.run.expect("an operation without a running task"); + let task = &mut self.tasks[run.task]; + let (_, op) = task.prog[task.pc]; + task.pc = (task.pc + 1) % task.prog.len(); + task.left = task.prog[task.pc].0; + match op { + Op::Spin => task.left = u64::MAX / 4, + Op::Yield => { + if !self.queue.is_empty() { + self.switch_in(Path::Yield); + self.enqueue(run.task); + } else if self.wiring == Wiring::YieldAloneMarks { + self.slice.entered(Entry::Between); + } + } + Op::Wait(_) | Op::Input(_) | Op::Exit => { + let path = match op { + Op::Wait(n) => { + task.state = State::Blocked; + task.deadline = self.ticks + n + 1; + Path::Block + } + Op::Input(after) => { + task.state = State::Blocked; + task.wake_at = self.now + after.max(1); + Path::Block + } + _ => { + task.state = State::Dead; + Path::Exit + } + }; + self.run = None; + if !self.queue.is_empty() { + self.switch_in(path); + } + } + } + } + + /// 다음 사건까지 시간을 보내고 그 사건 하나를 처리하는 함수입니다. 같은 + /// 시각이면 현재 태스크의 시스템 콜, 입력, 틱의 순서입니다(시스템 콜을 + /// 처리하는 동안 도착한 틱은 그 뒤에 받으므로). `tick_first`면 시스템 콜과 + /// 겹친 틱을 먼저 처리합니다(틱이 시스템 콜 바로 앞에 도착한 경우). + fn advance(&mut self) { + let next_tick = (self.ticks + 1) * P; + let input = self + .tasks + .iter() + .enumerate() + .filter(|(_, t)| t.state == State::Blocked && t.wake_at != 0) + .map(|(i, t)| (t.wake_at, i)) + .min(); + let op_at = self.run.map(|r| self.now + self.tasks[r.task].left); + let mut at = next_tick; + if let Some((w, _)) = input { + at = at.min(w); + } + if let Some(o) = op_at { + at = at.min(o); + } + if let Some(r) = self.run { + self.tasks[r.task].left -= at - self.now; + self.tasks[r.task].cpu += at - self.now; + } + self.now = at; + if op_at == Some(at) && !(self.tick_first && at == next_tick) { + self.do_op(); + } else if let Some((w, t)) = input.filter(|&(w, _)| w == at && w < next_tick) { + debug_assert_eq!(w, at); + self.tasks[t].wake_at = 0; + self.enqueue(t); + if self.run.is_none() { + self.switch_in(Path::IdleInput); + } + } else { + self.tick(); + } + } + + /// 시작한 뒤로 지난 시간 + fn elapsed(&self) -> u64 { + self.now - START + } + + /// 시작한 뒤로 `span`만큼 지날 때까지 돌리는 함수입니다. + fn run_for(&mut self, span: u64, mut each: impl FnMut(&Sim)) { + while self.elapsed() < span { + self.advance(); + each(self); + } + } +} + +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } +} + +/// 틱 경계 바로 앞뒤에 걸리는 길이가 자주 나오게 고른 무작위 프로그램 +fn random_prog(r: &mut Rng) -> Prog { + (0..1 + r.below(4)) + .map(|_| { + let run = match r.below(8) { + 0 => 1, + 1 => P - 1, + 2 => P, + 3 => P + 1, + 4 => 2 * P - 1, + _ => 1 + r.below(3 * P), + }; + let op = match r.below(20) { + 0..=7 => Op::Yield, + 8..=12 => Op::Wait(1 + r.below(3)), + 13..=16 => Op::Input(1 + r.below(3 * P)), + 17 => Op::Exit, + _ => Op::Spin, + }; + (run, op) + }) + .collect() +} + +fn random_sim(seed: u64, wiring: Wiring, tick_first: bool) -> Sim { + let mut r = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1); + let n = 2 + r.below(4); + let progs = (0..n).map(|_| random_prog(&mut r)).collect(); + let mut s = Sim::new(progs, wiring); + s.tick_first = tick_first; + s.run_for(300 * P, |_| {}); + s +} + +/// 끝없이 도는 태스크의 프로그램 +fn spinner() -> Prog { + vec![(1, Op::Spin)] +} + +/// 모형을 돌리면서 `victim`번 태스크의 몫을 지켜보는 함수입니다. 시작부터 어느 +/// 시점까지를 재도 그 태스크가 받은 시간이 "지난 시간의 1/n"에서 뒤처진 정도가 +/// 한계를 넘는 순간이 있었으면 false를 함께 줍니다. +/// +/// 한계는 그 태스크가 차례를 한 번 기다리는 동안 생길 수 있는 가장 큰 +/// 뒤처짐입니다. 다른 태스크 n-1개가 한 주기씩, 그리고 시작한 시각부터 첫 틱까지 +/// 입니다. 차례가 올 때마다 온전한 한 주기를 받으므로 뒤처짐은 쌓이지 않습니다. +fn watch_share(progs: Vec, victim: usize, wiring: Wiring, periods: u64) -> (Sim, bool) { + let n = progs.len() as u64; + let lag = (n - 1) * P + (P - START); + let mut kept = true; + let mut run = |tick_first| { + let mut s = Sim::new(progs.clone(), wiring); + s.tick_first = tick_first; + s.run_for(periods * P, |s| { + if s.tasks[victim].cpu * n + lag < s.elapsed() { + kept = false; + } + }); + s + }; + // 시스템 콜과 틱이 겹칠 때의 두 순서를 모두 돌리고, 돌려주는 모형은 시스템 + // 콜이 먼저인 쪽 + run(true); + let s = run(false); + (s, kept) +} + +/// 0번이 끝없이 도는 태스크이고 나머지가 주어진 프로그램인 모형을 돌리는 +/// 함수입니다. +fn against_a_spinner(others: Vec, wiring: Wiring, periods: u64) -> (Sim, bool) { + let mut progs = vec![spinner()]; + progs.extend(others); + watch_share(progs, 0, wiring, periods) +} + +fn permille(s: &Sim, t: usize) -> u64 { + s.tasks[t].cpu * 1000 / s.elapsed() +} + +#[test] +fn the_rule_alone() { + let mut s = Slice::new(); + assert_eq!(s.on_tick(), Verdict::Rotate); + s.entered(Entry::Between); + assert_eq!(s.on_tick(), Verdict::Keep); + assert_eq!(s.on_tick(), Verdict::Rotate); + assert_eq!(s.on_tick(), Verdict::Rotate); + // 면제는 쌓이지 않고, 틱에서 들어온 태스크는 앞 태스크의 면제를 물려받지 않음 + s.entered(Entry::Between); + s.entered(Entry::Between); + assert_eq!(s.on_tick(), Verdict::Keep); + assert_eq!(s.on_tick(), Verdict::Rotate); + s.entered(Entry::Between); + s.entered(Entry::Tick); + assert_eq!(s.on_tick(), Verdict::Rotate); + assert_eq!(Slice::default(), Slice::new()); + assert_eq!(Entry::after_idle(true), Entry::Tick); + assert_eq!(Entry::after_idle(false), Entry::Between); +} + +#[test] +fn a_task_is_never_cut_before_a_full_period() { + let (mut cuts, mut shortest) = (0, u64::MAX); + for seed in 1..=4000 { + for tick_first in [false, true] { + let s = random_sim(seed, Wiring::Kernel, tick_first); + assert_eq!(s.violations, 0, "seed {seed} tick first {tick_first}"); + cuts += s.cuts; + shortest = shortest.min(s.shortest_cut); + } + } + assert!(cuts > 100_000, "too few preemptions to mean anything: {cuts}"); + // 끊긴 구간은 모두 한 주기 이상이었고, 꼭 한 주기인 것도 있었음 + assert_eq!(shortest, P); +} + +#[test] +fn the_old_rule_and_every_wrong_wiring_are_caught() { + for wiring in [ + Wiring::Old, + Wiring::YieldAsTick, + Wiring::BlockAsTick, + Wiring::ExitAsTick, + Wiring::TickAsBetween, + Wiring::IdleTickAsBetween, + Wiring::IdleInputAsTick, + Wiring::BootAsTick, + Wiring::YieldAloneMarks, + ] { + let bad: u64 = (1..=400).map(|seed| random_sim(seed, wiring, false).violations).sum(); + assert!(bad > 0, "{wiring:?} was not caught"); + } + // 예전 방식에서는 한 주기보다 짧게 돌고 끊기는 구간이 실제로 나옴 + let shortest = (1..=400).map(|seed| random_sim(seed, Wiring::Old, false).shortest_cut).min(); + assert!(shortest.unwrap() < P / 10); +} + +#[test] +fn yielding_just_before_the_tick_no_longer_takes_the_cpu() { + // 공격하는 태스크 하나가 주기의 1%부터 99% 지점까지에서 양보함 + let (mut worst_old, mut worst_new) = (1000, 1000); + for pct in 1..100 { + let attacker = vec![(pct * P / 100, Op::Yield)]; + let (s, kept) = against_a_spinner(vec![attacker.clone()], Wiring::Kernel, 400); + assert!(kept, "yield at {pct}%"); + worst_new = worst_new.min(permille(&s, 0)); + let (s, _) = against_a_spinner(vec![attacker], Wiring::Old, 400); + worst_old = worst_old.min(permille(&s, 0)); + } + assert!(worst_new >= 499, "share fell to {worst_new} permille"); + assert!(worst_old <= 15, "the old rule must show the attack, got {worst_old} permille"); + + // QEMU에서 잰 경우와 같은 지점: 90% 지점에서 양보하면 예전에는 상대가 10%쯤만 + // 받았고 지금은 절반을 넘김 + let (s, _) = against_a_spinner(vec![vec![(90, Op::Yield)]], Wiring::Old, 400); + assert!((95..=105).contains(&permille(&s, 0)), "{}", permille(&s, 0)); + let (s, _) = against_a_spinner(vec![vec![(90, Op::Yield)]], Wiring::Kernel, 400); + assert!((545..=555).contains(&permille(&s, 0)), "{}", permille(&s, 0)); +} + +#[test] +fn the_task_behind_the_yielder_is_the_one_that_lost() { + // 0번이 공격하는 태스크, 1번이 그 바로 뒤에 선 태스크, 2번이 그다음 + let progs = || vec![vec![(90, Op::Yield)], spinner(), spinner()]; + let shares = |wiring| { + let mut s = Sim::new(progs(), wiring); + s.run_for(600 * P, |_| {}); + [permille(&s, 0), permille(&s, 1), permille(&s, 2)] + }; + let near = |got: [u64; 3], want: [u64; 3]| got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 3); + let old = shares(Wiring::Old); + assert!(near(old, [450, 50, 500]), "{old:?}"); + let new = shares(Wiring::Kernel); + assert!(near(new, [300, 367, 333]), "{new:?}"); +} + +#[test] +fn a_spinner_keeps_its_share_against_random_tasks() { + let mut old_failed = false; + for seed in 1..=3000u64 { + let mut r = Rng(seed.wrapping_mul(0x2545_F491_4F6C_DD1D) | 1); + let others: Vec = (0..1 + r.below(4)).map(|_| random_prog(&mut r)).collect(); + let (_, kept) = against_a_spinner(others.clone(), Wiring::Kernel, 200); + assert!(kept, "seed {seed}: {others:?}"); + old_failed |= !against_a_spinner(others, Wiring::Old, 200).1; + } + assert!(old_failed, "the old rule should lose the share in some schedule"); +} + +#[test] +fn a_spinner_keeps_its_share_against_colluding_tasks() { + // 공격하는 태스크 여럿이 저마다 다른 지점에서 양보하거나 기한 대기를 거는 + // 모든 조합(주기를 아홉 지점으로 나눔) + let points: Vec = (1..10).map(|i| i * P / 10 - 1).chain([P - 1]).collect(); + let choices: Vec<(u64, Op)> = points + .iter() + .flat_map(|&at| [(at, Op::Yield), (at, Op::Wait(1))]) + .collect(); + for attackers in 1..=3usize { + let mut pick = vec![0usize; attackers]; + 'grid: loop { + let others: Vec = pick.iter().map(|&i| vec![choices[i]]).collect(); + let (_, kept) = against_a_spinner(others, Wiring::Kernel, 120); + assert!(kept, "{attackers} attackers, choices {pick:?}"); + for slot in pick.iter_mut() { + *slot += 1; + if *slot < choices.len() { + continue 'grid; + } + *slot = 0; + } + break; + } + } +} + +#[test] +fn blocking_must_grant_the_exemption_too() { + // 양보에만 면제를 주면 블록으로 같은 일을 할 수 있음. 틱 바로 앞에서 번갈아 + // 기한 대기를 거는 두 태스크 사이에 선 태스크(1번)는 주기마다 한 칸만 받음 + let waiter = || vec![(P - 1, Op::Wait(1))]; + let progs = || vec![waiter(), spinner(), waiter()]; + let (s, kept) = watch_share(progs(), 1, Wiring::BlockAsTick, 400); + assert!(!kept && permille(&s, 1) <= 15, "share {} permille", permille(&s, 1)); + let (s, kept) = watch_share(progs(), 1, Wiring::Kernel, 400); + assert!(kept && permille(&s, 1) >= 333, "share {} permille", permille(&s, 1)); +} + +#[test] +fn waiting_costs_at_most_one_period_more_than_before() { + // 먼저 실행될 태스크가 k개일 때(실행 중인 태스크 포함), 예전 방식에서는 k주기 + // 안에 실행됐음. 지금은 k + 1주기 안임. 늘어난 만큼은 한 주기를 넘지 않고, + // 틱이 시스템 콜 바로 앞에 도착하는 순서에서는 꼭 한 주기까지 나타남 + let worst = |wiring, tick_first| { + (1..=3000).map(|seed| random_sim(seed, wiring, tick_first).worst_wait).max().unwrap() + }; + for tick_first in [false, true] { + assert_eq!(worst(Wiring::Old, tick_first), 0); + let now = worst(Wiring::Kernel, tick_first); + println!("worst wait beyond one period per task ahead (tick first {tick_first}): {now} of {P}"); + assert!(now > P as i64 / 2 && now <= P as i64, "{now}"); + } + assert_eq!(worst(Wiring::Kernel, true), P as i64); +} diff --git a/design/en/README.md b/design/en/README.md index baa07cf..2fb9842 100644 --- a/design/en/README.md +++ b/design/en/README.md @@ -23,7 +23,7 @@ Read them in the order of the following table the first time. This order follows | [uefi.md](uefi.md) | The UEFI loader: why it sits outside the kernel, its flow, which memory it refuses to call RAM, the device tree rewrite, the self-check before the jump, what QEMU cannot test, and what has been booted | | [hardening.md](hardening.md) | PAC key derivation, PAN, closing EL0 access to counters, debug and PMU, and the root task integrity check, including what each does not protect yet | | [exceptions.md](exceptions.md) | The vector table, saving user state, system call dispatch, and fault isolation | -| [scheduling.md](scheduling.md) | TCBs and their bound CNode and address space, task creation and teardown, the round-robin scheduler, and timer preemption | +| [scheduling.md](scheduling.md) | TCBs and their bound CNode and address space, task creation and teardown, the round-robin scheduler, and timer preemption, including the rule that a task switched in between two ticks is not cut by the first tick it meets | | [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 | diff --git a/design/en/exceptions.md b/design/en/exceptions.md index 04727c3..467d64e 100644 --- a/design/en/exceptions.md +++ b/design/en/exceptions.md @@ -141,7 +141,7 @@ In the second state nothing can wake a task today, because there are no notifica 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. +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 calls `k0_sched::on_tick`. That call moves the current task to the end of the ready queue and runs the next ready task only if the slice rule says this tick cuts the current task, see [scheduling.md](scheduling.md#the-slice-rule). 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. diff --git a/design/en/ipc.md b/design/en/ipc.md index fc12cc6..c4a3fa4 100644 --- a/design/en/ipc.md +++ b/design/en/ipc.md @@ -114,7 +114,7 @@ When the original capability of an endpoint is deleted, every task still queued Every wait can be bounded. A timeout is the upper 32 bits of the flags register `x1`, counted in scheduler ticks. The tick period is 1 second (a kernel constant), so the tick is the unit of every timeout. The following rules apply. -- **Deadline rule**: a timeout of n ticks ends at the (n+1)-th timer tick after the call. As long as ticks are handled on time, the wait lasts between n and n+1 tick periods. +- **Deadline rule**: a timeout of n ticks ends at the (n+1)-th timer tick after the call. As long as ticks are handled on time, the wait lasts between n and n+1 tick periods. The timeout makes the task ready at that point. When it runs depends on the ready queue (see [scheduling.md](scheduling.md#timeouts)). - **Lower bound, not wall-clock time**: the kernel runs with interrupts masked during every system call, and a long one such as a large `CAP_REVOKE` makes a tick late. The wait is then that much longer. - **0 means no deadline**: the task waits until its partner acts, as before. - **One deadline for a call**: the deadline of `CALL` covers both phases, waiting for a receiver and then waiting for the reply. @@ -191,7 +191,7 @@ If no byte is ready, the task waits in the state `BlockedConsole`. The wait work 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. +> Input waits behind running tasks. There are no priorities, so the latency of a byte is up to one tick per ready task, plus one more tick when the running task got the CPU between two ticks (see [scheduling.md](scheduling.md)). ## Errors @@ -257,10 +257,10 @@ The boot test script also requires an exact number of `k0: task fault` lines and > [!NOTE] > Capability transfer over IPC and notification objects do not exist yet. Timeouts are opt-in per call, so a task that waits without one still waits until its partner acts. -- **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)). +- **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 on a one-second tick. A task that got the CPU between two ticks keeps it through the next tick, so a woken task can wait one tick period longer than it did before. With k tasks to run before it, a task starts within k + 1 tick periods. These numbers describe this version of the scheduler and are not an interface (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. 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. +- **Input latency**: a `CONSOLE_READ` waiter is woken behind running tasks, so a byte can wait up to a tick per ready task, plus one more tick when the running task got the CPU between two ticks. - **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 6b1a435..49e308b 100644 --- a/design/en/scheduling.md +++ b/design/en/scheduling.md @@ -10,7 +10,7 @@ This note describes the following: - how K0 represents a task - how user space creates, starts and tears down tasks -- how the round-robin scheduler switches between tasks +- how the round-robin scheduler switches between tasks and decides when a timer tick cuts a task The code is in the following places: @@ -98,22 +98,47 @@ When an exception arrives from EL0, the vector code saves all user registers int Tasks can run in different address spaces, so `TTBR0_EL1` really changes between them. If an address space is destroyed while it is installed, the kernel first switches `TTBR0_EL1` to an empty table. -Three operations use this switch, as shown in the following table. +Five operations use this switch, as shown in the following table. Each one passes the entry kind of the next task: `Tick` if the task got the CPU by a tick's own decision, `Between` if it got it between two ticks. The next section explains why the kernel keeps this. -| Operation | Used by | What happens to the current task | -| --- | --- | --- | -| `rotate` | `YIELD`, timer preemption | goes to the tail of the ready queue, unless nothing else is ready, in which case it simply continues | -| `block_and_switch` | IPC, the idle loop, and the system call exit path when the current task died | stays out of the ready queue. The caller has already put it in an endpoint queue or behind a reply right, or it is `Dead`. | -| `handoff` | boot, once | the root task becomes the first `Running` task | +| Operation | Used by | What happens to the current task | Entry kind of the next task | +| --- | --- | --- | --- | +| `rotate` | `YIELD` | goes to the tail of the ready queue, unless nothing else is ready, in which case it simply continues | `Between` | +| `on_tick` | timer preemption | if it got the CPU between two ticks and has met no tick yet, it continues and the exemption is used up. Otherwise it goes to the tail of the ready queue, unless nothing else is ready | `Tick` | +| `block_and_switch` | IPC, `CONSOLE_READ`, and the system call exit path when the current task died | stays out of the ready queue. The caller has already put it in an endpoint queue, behind a reply right or in the console waiter slot, or it is `Dead`. | `Between` | +| `resume_from_idle` | the idle loop | (the current task is blocked or dead) | `Tick` if a tick passed while idle, otherwise `Between` | +| `handoff` | boot, once | the root task becomes the first `Running` task | `Between` | ## 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**. 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. +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`. That function wakes the console and timeout waiters that are due and then calls `k0_sched::on_tick`, which decides whether this tick cuts the current task (see [The slice rule](#the-slice-rule)). 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 or blocks therefore **loses the CPU after at most two seconds**, and after one second if it got the CPU at a tick. 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. 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. +A tick still cuts a task only when another task is ready. A timer interrupt that arrives at EL1 is possible only during boot, before the handoff, or while the kernel idles, and it only counts the tick. `on_tick` is called exactly once for every tick taken from EL0. 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 one tick per ready task, plus one more tick when the running task got the CPU between two ticks. + +## The slice rule + +The timer is armed only in the tick handler, never when the kernel switches tasks. A task that gets the CPU between two ticks therefore receives only the rest of a period. Before this rule, the next tick moved it to the end of the queue however short a time it had run. A task could call `YIELD`, which needs no capability, shortly before each tick. The task behind it then got only the sliver after the yield, and the yielding task was back at the head of the queue for the next full period. In a QEMU run with two CPU-bound tasks, the other task fell from about 52 % of the CPU to between 7.9 % and 11.1 % when the attacker yielded at 90 % of the period. The yield point in that run was set from a loop count that the root task had measured for the attacker. No attacker that finds the tick phase by itself was built. + +The rule is in the crate `k0-slice`, which only answers the question "does this tick cut the current task". The scheduler keeps one mark next to the current task and writes it only where the current task changes: + +- A task that gets the CPU **between two ticks** (`Entry::Between`) is not cut by the first tick it meets. That tick uses up the exemption, and the task runs on to the tick after it. This covers a previous task that called `YIELD`, blocked (IPC or `CONSOLE_READ`), exited or was killed, and a kernel that was idle and woke for something that was not a tick, such as console input. +- A task that gets the CPU **by a tick's own decision** (`Entry::Tick`) starts at the beginning of a period and is cut by the next tick, as before. That includes a task the idle kernel switches to after a tick woke it, for example an expired timeout. If a tick and console input arrive in the same wake-up, `Entry::after_idle` counts it as a tick. +- The root task at boot counts as entering between two ticks, because the timer already runs during boot. +- Waking a task never grants the exemption. A woken task goes to the end of the ready queue as before, and console input still does not preempt. +- `YIELD` with nothing else ready changes nothing. + +`Slice::entered` assigns the mark from the entry kind alone and never reads the previous value, so a mark left by the previous task cannot survive a switch. Blocking and exiting grant the exemption as well as `YIELD`. If only `YIELD` did, two tasks that start timed waits just before each tick would starve the task between them (the model shows this case). + +What follows from the rule: + +- A task that was switched in is not cut by the timer before it has had one full tick period, unless it gives up the CPU itself. Before a forced preemption it runs at least one period and at most two. +- With N ready tasks, a task that never yields or blocks keeps at least 1/N of the CPU in the long run, whatever the other tasks do with `YIELD`, blocking and timed waits. This was checked by search in a model (see [How it is tested](#how-it-is-tested)). It is **not a proof**, and it is **not a budget**: nothing caps what a task may use, and N grows with every task that is created. +- It costs latency. A task that becomes ready with k tasks to run before it (the running one included) used to start within k tick periods and now starts within k + 1. In the model, a caller and a server that exchange calls and replies behind one CPU-bound task need 4 ticks per round trip instead of 2. With no CPU-bound task nothing changes. + +> [!NOTE] +> The numbers in this section (one to two periods per run, k + 1 periods of waiting) describe this version of the scheduler. They are not an interface. The tick is still one second and timeouts are still counted in ticks. ## Timeouts @@ -161,7 +186,7 @@ The kernel no longer parks the core when no task can run. If the current task bl 1. It waits for the next interrupt (`k0_arch::irq::wait_for_interrupt`: `wfi` with IRQs masked, then a short unmask so that the EL1 vector takes the interrupt). 2. It wakes every IPC waiter whose deadline has passed. -3. It switches to a ready task if there is one, and otherwise waits again. +3. It switches to a ready task if there is one (`resume_from_idle`, which tells the slice rule whether a tick passed while idle), and otherwise waits again. 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: @@ -181,19 +206,35 @@ The scheduler and the system call paths read system registers, so they are teste - create a task that counts to a target and exits, and wait for it, - refuse to resume an unconfigured task, refuse to resume a task twice, and refuse to resume a dead task, -- start a task that spins forever without yielding, then confirm that the root task still gets the CPU back through timer preemption, +- run the slice test (`userspace/root-task/src/timeslice.rs`), which shows that a task which never yields is still preempted by the timer and that a task which got the CPU by a yield or by a block is not cut at its first tick, - confirm that thread pointer registers do not leak between tasks, - build confined tasks that have their own CNode and their own address space, and check that the root task's slot numbers mean nothing there, and - delete a task in each state (inactive, stopped, ready, blocked in send, receive and call, waiting for a reply, holding a reply right, and at the head, middle and tail of an endpoint queue), delete endpoints with tasks queued, kill a task by revoking its CNode or deleting its address space, and have a task delete its own TCB and revoke the untyped it was carved from. -`tools/qemu-boot-test.sh` requires the markers `root: child exit test pass`, `root: preempt test pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: revocation tests pass` and `root: sched tests pass`, followed by at least one more timer tick. The markers also include `k0: idle (waiting for a timeout)` and `root: timeout tests pass`, which come from the timeout tests (see [ipc.md](ipc.md)). It fails if the log contains a line that starts with `k0: all tasks`, `k0: FATAL` or `k0: PANIC`, so a run in which the kernel ends up with nothing to run and no timeout pending fails. It also counts task fault lines exactly (see [exceptions.md](exceptions.md)), which catches a task that keeps running after its teardown. +`tools/qemu-boot-test.sh` requires the markers `root: child exit test pass`, `root: slice test yield pass`, `root: slice test block pass`, `root: preempt test pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: revocation tests pass` and `root: sched tests pass`, followed by at least one more timer tick. The markers also include `k0: idle (waiting for a timeout)` and `root: timeout tests pass`, which come from the timeout tests (see [ipc.md](ipc.md)). It fails if the log contains a line that starts with `k0: all tasks`, `k0: FATAL` or `k0: PANIC`, so a run in which the kernel ends up with nothing to run and no timeout pending fails. It also counts task fault lines exactly (see [exceptions.md](exceptions.md)), which catches a task that keeps running after its teardown. + +The slice test replaces the old test with a busy child and a counter. EL0 has no clock, so it judges by order of execution, not by time. It starts four tasks: one that hands the CPU over (by `YIELD` in the first run, by blocking in the second), one that then spins for ever, one that leaves a mark the first time it runs, and a helper. The root task goes into a timed wait of one tick. If the spinning task is cut at its first tick, the marker task runs and the spinner sees the mark before the root task wakes. If it is not cut, the root task wakes first. The test logs `root: slice test yield pass`, `root: slice test block pass` and then `root: preempt test pass`, and on failure `root: FAIL slice: a task that got the cpu by a yield was cut at its first tick` (or `by a block`). Each run takes about 2 ticks, so the two runs add about 4 seconds to every boot test where the old test took about 1. + +The rule itself is tested on the host in the crate `k0-slice` (9 tests, run by `tools/host-test.sh`). The tests run the rule on a model of the scheduler with a first in first out ready queue, ticks, timed waits, input wake-ups at arbitrary times, exits and the idle case: + +- A check written separately from the rule agrees with every tick decision over 4,000 random schedules, in both orders in which a system call and a tick can fall on the same instant, and no preempted run was shorter than one period. +- The old rule and nine wrong ways of connecting the rule to the scheduler are each caught by that check. +- The share of a CPU-bound task holds against one yielding task at every percent of the period, against up to three cooperating tasks over a grid of yields and timed waits, and against 3,000 sets of random tasks. +- The two measured cases are reproduced (10 % and 55 % at a 90 % yield, and with three tasks 5 % for the task behind the yielder under the old rule). + +This is a search in a bounded model (up to 6 tasks), **not a proof**. Each of nine deliberate breaks of the rule fails at least one host test. With the kernel connection broken on purpose, the boot test fails for the old rule, for `YIELD` passing the wrong entry kind and for blocking passing the wrong entry kind. The boot test would not see the tick's own switch passing `Between`, the idle loop reporting the wrong thing about a tick, or the wrong entry kind at `handoff`. Those mistakes change how long a task runs before it is cut, not its share, and the host model covers the rule for these cases but not the kernel's use of it. + +With the change in QEMU, an attacker that yields at 90 % of the period left the other task 53.8 % to 54.9 % of the CPU (three runs). With three tasks no task was below 29.7 %. With an attacker that starts a timed wait just before the tick instead of yielding, the other task had 56.5 %. Everything ran in QEMU (TCG and HVF), nothing ran on hardware, and the yield point was set for the attacker, so what an attacker needs to find it by itself was not measured. ## Known gaps > [!NOTE] > Priorities and CPU budgets do not exist yet. There is one core only. -- **Scheduling**: plain round robin with a fixed one-second slice. A task that holds untyped memory can create many tasks and dilute everybody's share. +- **Scheduling**: round robin with a one-second tick and the slice rule. There is no priority and no CPU budget: a CPU-bound task uses its whole turn and nothing caps it. A task that holds untyped memory can still create many tasks and dilute everybody's share. +- **Timing channels**: they are open. A task still changes when, and now also for how long, another task runs by choosing when to yield or block. This has not been analysed. Closing it would need fixed time partitions, which K0 does not have. +- **Latency**: there is no real-time or latency promise. The tick is one second and the kernel is not preemptible. +- **Slice rule checks**: the host model covers the rule, not the kernel's use of it (see [How it is tested](#how-it-is-tested)), and the measurements ran only in QEMU with an attacker whose yield point was set for it. - **Timeouts**: they say when a task becomes ready, not when it runs. They are opt-in per call, so a task that waits without one can wait forever. - **Idle state**: it exists, but while the root task keeps calling `YIELD` after its self-tests, the CPU does not sleep. When no task is ready and no waiter has a deadline, the machine stays idle and nothing can wake a task. - **Availability**: a task that blocks without a timeout, including a confined one, can stay blocked for good if its partner never acts (GHSA-q99x-2wrv-358p). The kernel is not preemptible, so a long system call such as `CAP_REVOKE` on an untyped with many objects delays every other task and every timeout. Task isolation does not cover availability. diff --git a/design/en/terminal.md b/design/en/terminal.md index fedecaa..f1ac481 100644 --- a/design/en/terminal.md +++ b/design/en/terminal.md @@ -137,7 +137,7 @@ The vault side changed with this feature. There are four roles by endpoint badge ## 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. +**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 363 tests on an ARM host and 277 on other hosts (`k0-slice` adds 9). **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. @@ -153,7 +153,7 @@ The vault side changed with this feature. There are four roles by endpoint badge - **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. +- **Latency**: input waits behind running tasks. There are no priorities, so the latency is up to a tick per ready task, plus one more tick when the running task got the CPU between two ticks (see [scheduling.md](scheduling.md)). - **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). diff --git a/design/en/uefi.md b/design/en/uefi.md index 6c016a2..869ffdc 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 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. +- **Host test script**: `tools/host-test.sh` now runs 363 tests on an ARM host (`k0-abi` 15, `k0-cap` 44, `k0-boot` 85, `k0-efi` 33, `k0-conin` 15, `k0-slice` 9, `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 277 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. diff --git a/design/en/vault.md b/design/en/vault.md index 893eb05..3e2b74a 100644 --- a/design/en/vault.md +++ b/design/en/vault.md @@ -156,7 +156,7 @@ $ cargo build -p k0-kernel --features console,vault-ed25519 - 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 354 tests on an ARM host and 268 on other hosts (without `k0-mm`). +With the other crates, the host suite has 363 tests on an ARM host and 277 on other hosts (without `k0-mm`), and `k0-slice` adds 9 of them. **Root task self-test** (`test_oracle` in `userspace/root-task/src/oracle.rs`, only in images built with `vault`). It checks the following: @@ -183,7 +183,7 @@ The marker is `root: oracle tests pass`. The client tasks run one after another - **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)). +- **Availability is not protected**: clients share one endpoint and must use timeouts on every call (see [ipc.md](ipc.md)). Behind one CPU-bound task, a caller and the vault need 4 ticks per round trip in the scheduler model, where they needed 2. The terminal's calls use a 5 tick timeout, and the fixed image has no CPU-bound task in service mode. - **The root task is trusted**: it builds the vault and could read it. - **No client identity**: all signers share the one key. - **Entropy**: the seed is as good as its inputs. The key does not come from an approved random bit generator. diff --git a/design/kr/README.md b/design/kr/README.md index faa7f0f..56dcaa9 100644 --- a/design/kr/README.md +++ b/design/kr/README.md @@ -23,7 +23,7 @@ | [uefi_KR.md](uefi_KR.md) | UEFI 로더: 커널 밖에 두는 이유, 실행 흐름, RAM으로 인정하지 않는 메모리, 디바이스 트리 재작성, 점프 전 자가 검사, QEMU로 테스트할 수 없는 것, 부팅해 본 환경 | | [hardening_KR.md](hardening_KR.md) | PAC 키 파생, PAN, 카운터·디버그·PMU에 대한 EL0 접근 차단, 루트 태스크 무결성 검사와 각각이 아직 보호하지 못하는 것 | | [exceptions_KR.md](exceptions_KR.md) | 벡터 테이블, 사용자 상태 저장, 시스템 콜 디스패치, 폴트 격리 | -| [scheduling_KR.md](scheduling_KR.md) | TCB와 거기에 묶인 CNode, 주소 공간, 태스크 생성과 정리, 라운드 로빈 스케줄러, 타이머 선점 | +| [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 권한, 대기와 깨우기, 터미널의 연결과 적대적 태스크 점검, 화면과 명령 규칙, 테스트, 알려진 공백 | diff --git a/design/kr/exceptions_KR.md b/design/kr/exceptions_KR.md index 5148536..2560d44 100644 --- a/design/kr/exceptions_KR.md +++ b/design/kr/exceptions_KR.md @@ -141,7 +141,7 @@ k0: task fault dabort-lower (esr 0x92000046 elr 0x400398 far 0x0), killing task 커널이 항상 켜는 인터럽트는 **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 ...`를 출력하고 파킹합니다. +EL0에서 받은 IRQ는 시스템 콜과 같은 방식으로 저장됩니다. 핸들러는 인터럽트를 확인합니다. 타이머였다면 타이머를 1초 뒤로 다시 설정하고 `k0: tick N`을 출력합니다. 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔에 출력하며, 로그에는 처음 4개의 tick 줄만 남깁니다. 그다음 `k0_preempt`를 호출합니다. 이 함수는 먼저 기한이 된 IPC 타임아웃을 만료시키고(`k0_ipc::expire_timeouts`), 그래서 기한이 지난 대기자는 라운드 로빈 전환 전에 준비 상태가 됩니다. 그런 다음 `k0_sched::on_tick`을 호출합니다. 슬라이스 규칙이 이번 틱이 현재 태스크를 끊는다고 할 때만 현재 태스크를 준비 큐의 맨 뒤로 보내고 다음 준비 태스크를 실행합니다. 규칙은 [scheduling_KR.md](scheduling_KR.md#슬라이스-규칙)를 참고하세요. 1020부터 1023까지의 가짜 인터럽트 번호는 무시합니다. 그 외의 인터럽트 번호와 모든 FIQ는 설계상 발생할 수 없으므로 커널은 `k0: UNEXPECTED ...`를 출력하고 파킹합니다. 틱을 센 뒤 핸들러는 콘솔 수신 링도 비우며(`console-input` 이미지), 태스크가 콘솔 입력을 읽기 시작한 뒤에는 주기적인 틱 줄을 출력하지 않습니다([boot_KR.md](boot_KR.md) 참고). 틱, 선점, 타임아웃은 그대로입니다. diff --git a/design/kr/ipc_KR.md b/design/kr/ipc_KR.md index 96af3ed..d20e3df 100644 --- a/design/kr/ipc_KR.md +++ b/design/kr/ipc_KR.md @@ -114,7 +114,7 @@ K0의 IPC는 seL4 방식의 **동기 랑데부**입니다. 메시지는 레지 모든 대기에 상한을 걸 수 있습니다. 타임아웃은 플래그 레지스터 `x1`의 상위 32비트이며 스케줄러 틱 단위입니다. 틱 주기는 1초(커널 상수)이므로 모든 타임아웃의 단위는 틱입니다. 다음 규칙이 적용됩니다. -- **기한 규칙**: n 틱의 타임아웃은 호출 뒤 (n+1)번째 타이머 틱에서 끝납니다. 틱이 제때 처리되는 한 대기는 틱 주기의 n배에서 n+1배 사이입니다. +- **기한 규칙**: n 틱의 타임아웃은 호출 뒤 (n+1)번째 타이머 틱에서 끝납니다. 틱이 제때 처리되는 한 대기는 틱 주기의 n배에서 n+1배 사이입니다. 타임아웃은 그 시점에 태스크를 준비 상태로 만들 뿐입니다. 실제로 실행되는 시점은 준비 큐에 달려 있습니다([scheduling_KR.md](scheduling_KR.md#타임아웃) 참고). - **하한이지 벽시계 시간이 아님**: 커널은 모든 시스템 콜을 인터럽트를 마스크한 채 실행하고, 큰 `CAP_REVOKE`처럼 긴 호출은 틱을 늦춥니다. 그러면 대기도 그만큼 길어집니다. - **0은 기한 없음**: 이전처럼 상대방이 동작할 때까지 기다립니다. - **호출의 기한은 하나**: `CALL`의 기한은 수신자를 기다리는 단계와 응답을 기다리는 단계를 모두 덮습니다. @@ -191,7 +191,7 @@ TCB에는 `deadline`, `tnext`, `tprev` 필드가 있습니다. `k0-sched`는 기 수신 인터럽트는 태스크가 권한을 가지고 처음 콘솔 입력을 읽을 때까지 꺼져 있습니다. 그 첫 읽기는 장치가 쥔 입력을 버리고, `k0: tick lines off (console input in use)` 한 줄을 출력한 뒤 주기적인 `k0: tick N` 줄을 멈춥니다. 틱, 선점, 타임아웃은 계속 동작합니다. 수신 경로와 그 한계는 [USAGE_KR.md](../../USAGE_KR.md)와 [exceptions_KR.md](exceptions_KR.md)에 있습니다. > [!NOTE] -> 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 바이트의 지연은 준비된 태스크마다 최대 한 틱입니다. +> 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 바이트의 지연은 준비된 태스크마다 최대 한 틱이며, 실행 중인 태스크가 두 틱 사이에 CPU를 받았다면 한 틱이 더해집니다([scheduling_KR.md](scheduling_KR.md) 참고). ## 오류 @@ -257,10 +257,10 @@ IPC와 해체는 부팅으로 테스트합니다. 루트 태스크는 서버 태 > [!NOTE] > IPC를 통한 케이퍼빌리티 전송과 Notification 오브젝트는 아직 없습니다. 타임아웃은 호출마다 선택하는 것이므로, 타임아웃 없이 기다리는 태스크는 여전히 상대방이 동작할 때까지 기다립니다. -- **타임아웃은 태스크가 준비되는 시점이지 실행되는 시점이 아님**: 우선순위도 CPU 예산도 없으며, 스케줄러는 1틱 슬라이스의 라운드 로빈입니다([scheduling_KR.md](scheduling_KR.md) 참고). +- **타임아웃은 태스크가 준비되는 시점이지 실행되는 시점이 아님**: 우선순위도 CPU 예산도 없으며, 스케줄러는 1초 틱 기준의 라운드 로빈입니다. 두 틱 사이에 CPU를 받은 태스크는 다음 틱까지 CPU를 유지하므로, 깨어난 태스크는 이전보다 한 틱 주기 더 기다릴 수 있습니다. 앞에 실행할 태스크가 k개이면 k + 1 틱 주기 안에 시작합니다. 이 수치는 이 버전의 스케줄러를 설명할 뿐 인터페이스가 아닙니다([scheduling_KR.md](scheduling_KR.md) 참고). - **긴 시스템 콜**: 커널은 선점되지 않으므로, 객체가 많은 untyped에 대한 `CAP_REVOKE` 같은 긴 호출은 다른 모든 태스크와 모든 타임아웃을 지연시킵니다. - **치명적 정지**: `k0_arch::fatal`이나 커널 패닉은 여전히 머신을 정지시킵니다. - **EL0의 시간 소스**: 틱에 맞춰 깨어나는 성질을 타이밍 공격에 쓸 수 있는지는 분석하지 않았습니다. 콘솔 입력이 있는 이미지에서는 외부의 누군가가 태스크가 실행되는 동안 인터럽트를 일으킬 수 있고(읽는 쪽이 속도를 정함), 읽는 태스크는 틱보다 세밀한 도착 시각을 압니다. 다른 태스크도 빼앗긴 시간을 알아챌 수 있습니다. 이 타이밍 채널도 분석하지 않았습니다. -- **입력 지연**: `CONSOLE_READ` 대기자는 실행 중인 태스크 뒤에서 깨어나므로 바이트는 준비된 태스크마다 최대 한 틱을 기다릴 수 있습니다. +- **입력 지연**: `CONSOLE_READ` 대기자는 실행 중인 태스크 뒤에서 깨어나므로 바이트는 준비된 태스크마다 최대 한 틱을 기다릴 수 있고, 실행 중인 태스크가 두 틱 사이에 CPU를 받았다면 한 틱을 더 기다립니다. - **큐에 있던 송신자**: 회수 뒤에도 메시지를 한 번 전달합니다. 엔드포인트에서 이미 기다리는 송신자는 자신을 큐에 세운 송신의 배지를 유지합니다. 기다리는 동안 그 케이퍼빌리티가 회수되어도 메시지는 다음 수신자에게 한 번 전달됩니다. - **메시지당 워드 네 개**: 더 큰 데이터는 공유 메모리가 필요합니다. 태스크가 서로 다른 주소 공간에서 실행될 수 있으므로, 공유 메모리는 그 태스크의 `AddrSpace` 케이퍼빌리티를 가진 쪽이 해당 주소 공간에 매핑해 주어야 합니다. diff --git a/design/kr/scheduling_KR.md b/design/kr/scheduling_KR.md index 828fffc..6340985 100644 --- a/design/kr/scheduling_KR.md +++ b/design/kr/scheduling_KR.md @@ -10,7 +10,7 @@ - K0가 태스크를 표현하는 방법 - 사용자 공간이 태스크를 만들고 시작하고 정리하는 방법 -- 라운드 로빈 스케줄러가 태스크 사이를 전환하는 방법 +- 라운드 로빈 스케줄러가 태스크 사이를 전환하고, 타이머 틱이 태스크를 끊을지 정하는 방법 코드는 다음 위치에 있습니다. @@ -98,22 +98,47 @@ 태스크마다 다른 주소 공간에서 실행될 수 있으므로 `TTBR0_EL1`은 태스크 사이에서 실제로 바뀝니다. 설치돼 있는 주소 공간이 파괴될 때는 커널이 먼저 `TTBR0_EL1`을 빈 테이블로 바꿉니다. -이 전환을 사용하는 동작은 다음 표와 같이 세 가지입니다. +이 전환을 사용하는 동작은 다음 표와 같이 다섯 가지입니다. 각 동작은 다음 태스크의 진입 종류를 함께 넘깁니다. 틱의 판정으로 CPU를 받았으면 `Tick`, 틱과 틱 사이에 받았으면 `Between`입니다. 커널이 이를 유지하는 까닭은 다음 절에서 설명합니다. -| 동작 | 사용처 | 현재 태스크에 일어나는 일 | -| --- | --- | --- | -| `rotate` | `YIELD`, 타이머 선점 | 준비 큐의 꼬리로 가고, 준비된 다른 태스크가 없으면 그대로 계속 실행 | -| `block_and_switch` | IPC, idle 루프, 그리고 현재 태스크가 죽었을 때의 시스템 콜 종료 경로 | 준비 큐 밖에 머뭅니다. 호출자가 이미 엔드포인트 큐나 응답 자격 뒤에 걸어 두었거나, 태스크가 `Dead`입니다. | -| `handoff` | 부트, 한 번 | 루트 태스크가 첫 `Running` 태스크가 됨 | +| 동작 | 사용처 | 현재 태스크에 일어나는 일 | 다음 태스크의 진입 종류 | +| --- | --- | --- | --- | +| `rotate` | `YIELD` | 준비 큐의 꼬리로 가고, 준비된 다른 태스크가 없으면 그대로 계속 실행 | `Between` | +| `on_tick` | 타이머 선점 | 틱과 틱 사이에 CPU를 받았고 아직 틱을 맞은 적이 없으면 계속 실행하며 면제를 소모합니다. 그렇지 않으면 준비 큐의 꼬리로 가고, 준비된 다른 태스크가 없으면 그대로 계속 실행 | `Tick` | +| `block_and_switch` | IPC, `CONSOLE_READ`, 그리고 현재 태스크가 죽었을 때의 시스템 콜 종료 경로 | 준비 큐 밖에 머뭅니다. 호출자가 이미 엔드포인트 큐, 응답 자격 뒤, 콘솔 대기자 슬롯 중 하나에 걸어 두었거나, 태스크가 `Dead`입니다. | `Between` | +| `resume_from_idle` | idle 루프 | (현재 태스크는 블록됐거나 죽음) | 대기 중 틱이 지나갔으면 `Tick`, 아니면 `Between` | +| `handoff` | 부트, 한 번 | 루트 태스크가 첫 `Running` 태스크가 됨 | `Between` | ## 선점 -타이머는 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)`를 남기고 틱 줄이 멈추지만, 틱과 선점과 타임아웃은 계속됩니다. +타이머는 1초에 한 번 발생합니다. EL0가 실행 중일 때 발생하면 IRQ 경로가 인터럽트를 확인하고 타이머를 다시 설정한 뒤 `k0: tick N`을 출력하고 `k0_preempt`를 호출합니다. `k0_preempt`는 기한이 된 콘솔 대기자와 타임아웃 대기자를 깨운 다음 `k0_sched::on_tick`을 호출하고, `on_tick`이 이번 틱이 현재 태스크를 끊을지 정합니다([슬라이스 규칙](#슬라이스-규칙) 참고). `k0: tick N`은 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔에 출력하며, 로그에는 처음 4개의 tick 줄만 남깁니다. 양보하지도 블록하지도 않는 태스크는 **최대 2초 뒤에는 CPU를 잃고**, 틱에서 CPU를 받았다면 1초 뒤에 잃습니다. 태스크가 콘솔 입력을 읽은 뒤에는 줄 하나 `k0: tick lines off (console input in use)`를 남기고 틱 줄이 멈추지만, 틱과 선점과 타임아웃은 계속됩니다. > [!IMPORTANT] > 커널 자체는 선점되지 않습니다. 예외 진입이 인터럽트를 마스크하고, 커널은 시스템 콜이나 폴트를 처리하는 동안 마스크를 유지합니다. -EL1에서 타이머 인터럽트가 도착하는 것은 이양 전 부트 중에만 가능하며, 그때는 틱을 세기만 합니다. `console-input` 이미지에서 입력 바이트가 도착해도 선점하지 않습니다. 깨어난 읽는 쪽은 다른 깨어난 태스크처럼 준비 큐의 맨 뒤로 갑니다. 우선순위가 없으므로 입력 지연은 준비된 태스크마다 최대 한 틱입니다. +틱은 여전히 준비된 다른 태스크가 있을 때만 태스크를 끊습니다. EL1에서 타이머 인터럽트가 도착하는 것은 이양 전 부트 중이나 커널이 대기하는 동안에만 가능하며, 그때는 틱을 세기만 합니다. `on_tick`은 EL0에서 받은 틱마다 정확히 한 번 호출됩니다. `console-input` 이미지에서 입력 바이트가 도착해도 선점하지 않습니다. 깨어난 읽는 쪽은 다른 깨어난 태스크처럼 준비 큐의 맨 뒤로 갑니다. 우선순위가 없으므로 입력 지연은 준비된 태스크마다 최대 한 틱이고, 실행 중인 태스크가 틱과 틱 사이에 CPU를 받았다면 한 틱이 더해집니다. + +## 슬라이스 규칙 + +타이머는 틱 핸들러에서만 다시 설정하며, 커널이 태스크를 전환할 때는 건드리지 않습니다. 그래서 틱과 틱 사이에 CPU를 받은 태스크는 주기의 남은 조각만 받습니다. 이 규칙이 생기기 전에는 얼마나 짧게 실행했든 다음 틱이 그 태스크를 큐의 끝으로 보냈습니다. 태스크가 매 틱 직전에 `YIELD`를 호출할 수 있었고, `YIELD`에는 케이퍼빌리티가 필요 없습니다. 그러면 뒤에 선 태스크는 양보 뒤의 조각만 받고, 양보한 태스크는 다음 온전한 주기를 위해 큐의 맨 앞으로 돌아옵니다. CPU를 계속 쓰는 태스크 둘을 QEMU에서 돌린 실행에서, 공격 태스크가 주기의 90 %에서 양보하면 다른 태스크의 몫이 약 52 %에서 7.9 %부터 11.1 % 사이로 떨어졌습니다. 이 실행의 양보 지점은 루트 태스크가 공격 태스크를 위해 측정한 반복 횟수로 정했습니다. 틱의 위상을 스스로 찾아내는 공격 태스크는 만들지 않았습니다. + +규칙은 크레이트 `k0-slice`에 있으며, 이 크레이트는 "이번 틱이 현재 태스크를 끊는가"라는 물음에만 답합니다. 스케줄러는 현재 태스크 옆에 표시를 하나 두고, 현재 태스크가 바뀌는 곳에서만 그 표시를 기록합니다. + +- 틱과 틱 사이에 CPU를 받은 태스크(`Entry::Between`)는 처음 맞는 틱에 끊기지 않습니다. 그 틱이 면제를 소모하고, 태스크는 그다음 틱까지 실행합니다. 앞선 태스크가 `YIELD`를 호출했거나, 블록됐거나(IPC 또는 `CONSOLE_READ`), 종료됐거나 죽은 경우, 그리고 커널이 대기하다가 콘솔 입력처럼 틱이 아닌 일로 깨어난 경우가 여기에 해당합니다. +- 틱의 판정으로 CPU를 받은 태스크(`Entry::Tick`)는 주기의 처음에 들어온 것이므로 이전처럼 다음 틱에서 끊깁니다. 틱이 깨운 뒤(예를 들어 기한이 지난 타임아웃) 대기 중이던 커널이 전환해 준 태스크도 여기에 속합니다. 틱과 콘솔 입력이 같은 깨어남에 함께 오면 `Entry::after_idle`이 틱으로 셉니다. +- 부트 때의 루트 태스크는 틱과 틱 사이에 들어온 것으로 셉니다. 타이머가 부트 중에 이미 돌고 있기 때문입니다. +- 태스크를 깨우는 것은 면제를 주지 않습니다. 깨어난 태스크는 이전처럼 준비 큐의 맨 뒤로 가고, 콘솔 입력은 여전히 선점하지 않습니다. +- 준비된 다른 태스크가 없을 때의 `YIELD`는 아무것도 바꾸지 않습니다. + +`Slice::entered`는 진입 종류만으로 표시를 대입하고 이전 값을 읽지 않으므로, 앞 태스크가 남긴 표시가 전환을 넘어 살아남지 않습니다. 면제는 `YIELD`뿐 아니라 블록과 종료에도 줍니다. `YIELD`만 주면, 틱 직전마다 타임아웃 대기를 시작하는 두 태스크가 그 사이의 태스크를 굶길 수 있습니다(모델이 이 경우를 보여 줍니다). + +규칙에서 따라 나오는 것은 다음과 같습니다. + +- 전환돼 들어온 태스크는 스스로 CPU를 내놓지 않는 한 온전한 한 틱 주기를 채우기 전에는 타이머에 끊기지 않습니다. 강제로 선점되기 전에 적어도 한 주기, 많아야 두 주기를 실행합니다. +- 준비된 태스크가 N개일 때 양보하지도 블록하지도 않는 태스크는 다른 태스크가 `YIELD`, 블록, 타임아웃 대기를 어떻게 하든 오래 보면 CPU의 1/N 이상을 유지합니다. 이는 모델에서 탐색으로 확인했습니다([테스트 방법](#테스트-방법) 참고). **증명이 아니며**, **예산도 아닙니다**. 태스크가 쓸 수 있는 양에 상한이 없고, 태스크를 만들 때마다 N이 늘어납니다. +- 대가는 지연입니다. 앞에 실행할 태스크가 k개(실행 중인 것 포함)인 채로 준비된 태스크는 예전에는 k 틱 주기 안에 시작했고, 지금은 k + 1 주기 안에 시작합니다. 모델에서는 CPU를 계속 쓰는 태스크 하나 뒤에서 호출과 응답을 주고받는 호출자와 서버가 왕복마다 2틱 대신 4틱이 필요합니다. CPU를 계속 쓰는 태스크가 없으면 달라지는 것이 없습니다. + +> [!NOTE] +> 이 절의 수치(실행당 한 주기부터 두 주기, 대기 k + 1 주기)는 이 버전 스케줄러의 동작을 설명할 뿐 인터페이스가 아닙니다. 틱은 여전히 1초이고 타임아웃은 여전히 틱 단위로 셉니다. ## 타임아웃 @@ -161,7 +186,7 @@ EL1에서 타이머 인터럽트가 도착하는 것은 이양 전 부트 중에 1. 다음 인터럽트를 기다립니다(`k0_arch::irq::wait_for_interrupt`: IRQ를 마스크한 `wfi`, 그다음 EL1 벡터가 인터럽트를 받도록 잠깐 마스크 해제). 2. 기한이 지난 IPC 대기자를 모두 깨웁니다. -3. 준비된 태스크가 있으면 그 태스크로 전환하고, 없으면 다시 기다립니다. +3. 준비된 태스크가 있으면 그 태스크로 전환하고(`resume_from_idle`, 대기 중 틱이 지나갔는지를 슬라이스 규칙에 알려 줍니다), 없으면 다시 기다립니다. 커널이 idle 상태인 동안에도 타이머 틱은 계속 세고 처리합니다. idle 루프는 다음 두 줄 가운데 하나를 부팅당 최대 한 번씩 출력합니다. @@ -181,19 +206,35 @@ EL0에서 받은 SError는 여전히 머신 전체를 정지시키며, `k0_arch: - 목표값까지 세고 종료하는 태스크를 만들고 기다림 - 구성되지 않은 태스크, 이미 재개한 태스크, 죽은 태스크의 재개를 거부 -- 양보 없이 무한 루프를 도는 태스크를 시작하고, 타이머 선점으로 루트 태스크가 CPU를 되찾는지 확인 +- 슬라이스 테스트(`userspace/root-task/src/timeslice.rs`) 실행: 양보하지 않는 태스크가 여전히 타이머에 선점되는지, 그리고 양보나 블록으로 CPU를 받은 태스크가 처음 맞는 틱에 끊기지 않는지 확인 - 스레드 포인터 레지스터가 태스크 사이에 새지 않는지 확인 - 자기 CNode와 자기 주소 공간을 가진 격리 태스크를 만들고, 루트 태스크의 슬롯 번호가 거기서 아무 의미가 없는지 확인 - 모든 상태(inactive, stopped, ready, send·receive·call에서 블록, 응답 대기, 응답 자격 보유, 엔드포인트 큐의 머리·중간·꼬리)의 태스크 삭제, 태스크가 줄 서 있는 엔드포인트 삭제, CNode 회수 또는 주소 공간 삭제로 태스크 종료, 태스크가 자기 TCB를 삭제하고 자신이 잘려 나온 untyped를 회수하는 경우 -`tools/qemu-boot-test.sh`는 마커 `root: child exit test pass`, `root: preempt test pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: revocation tests pass`, `root: sched tests pass`를 요구하고, 그 뒤에 타이머 틱이 적어도 하나 더 나와야 합니다. 마커에는 타임아웃 테스트가 출력하는 `k0: idle (waiting for a timeout)`와 `root: timeout tests pass`도 포함됩니다([ipc_KR.md](ipc_KR.md) 참고). 로그에 `k0: all tasks`로 시작하는 줄, `k0: FATAL`, `k0: PANIC`이 있으면 실패하므로 실행할 태스크도 대기 중인 타임아웃도 없는 상태에 이른 실행은 실패로 처리됩니다. 태스크 폴트 줄도 정확한 개수로 세므로([exceptions_KR.md](exceptions_KR.md) 참고), 정리된 뒤에도 계속 실행되는 태스크를 잡아냅니다. +`tools/qemu-boot-test.sh`는 마커 `root: child exit test pass`, `root: slice test yield pass`, `root: slice test block pass`, `root: preempt test pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: revocation tests pass`, `root: sched tests pass`를 요구하고, 그 뒤에 타이머 틱이 적어도 하나 더 나와야 합니다. 마커에는 타임아웃 테스트가 출력하는 `k0: idle (waiting for a timeout)`와 `root: timeout tests pass`도 포함됩니다([ipc_KR.md](ipc_KR.md) 참고). 로그에 `k0: all tasks`로 시작하는 줄, `k0: FATAL`, `k0: PANIC`이 있으면 실패하므로 실행할 태스크도 대기 중인 타임아웃도 없는 상태에 이른 실행은 실패로 처리됩니다. 태스크 폴트 줄도 정확한 개수로 세므로([exceptions_KR.md](exceptions_KR.md) 참고), 정리된 뒤에도 계속 실행되는 태스크를 잡아냅니다. + +슬라이스 테스트는 바쁜 자식과 카운터를 쓰던 예전 테스트를 대신합니다. EL0에는 시계가 없으므로 시간이 아니라 실행 순서로 판정합니다. 태스크 넷을 시작합니다. CPU를 넘기는 태스크(첫 실행에서는 `YIELD`로, 두 번째 실행에서는 블록으로), 그 뒤에 영원히 도는 태스크, 처음 실행될 때 표시를 남기는 태스크, 도우미입니다. 루트 태스크는 한 틱짜리 타임아웃 대기에 들어갑니다. 도는 태스크가 처음 맞는 틱에 끊기면 표시 태스크가 실행되어, 루트 태스크가 깨기 전에 도는 태스크가 표시를 봅니다. 끊기지 않으면 루트 태스크가 먼저 깹니다. 테스트는 `root: slice test yield pass`, `root: slice test block pass`, 그다음 `root: preempt test pass`를 출력하고, 실패하면 `root: FAIL slice: a task that got the cpu by a yield was cut at its first tick`(또는 `by a block`)을 출력합니다. 한 번 실행에 약 2틱이 들므로, 예전 테스트가 약 1초였던 자리에 두 번의 실행이 부팅 테스트마다 약 4초를 더합니다. + +규칙 자체는 크레이트 `k0-slice`의 호스트 테스트(9개, `tools/host-test.sh`가 실행)로 확인합니다. 테스트는 선입선출 준비 큐, 틱, 타임아웃 대기, 임의의 시각에 오는 입력 깨우기, 종료, idle 경우를 갖춘 스케줄러 모델 위에서 규칙을 돌립니다. + +- 규칙과 따로 작성한 검사가 무작위 일정 4,000개에서 모든 틱 판정과 일치합니다. 시스템 콜과 틱이 같은 순간에 놓일 수 있는 두 순서 모두에서 그렇고, 선점된 실행 가운데 한 주기보다 짧은 것은 없었습니다. +- 예전 규칙과, 규칙을 스케줄러에 잘못 연결하는 아홉 가지 방법이 각각 그 검사에 걸립니다. +- CPU를 계속 쓰는 태스크의 몫은 주기의 모든 퍼센트에서 양보하는 태스크 하나를 상대로, 양보와 타임아웃 대기의 격자에서 협력하는 태스크 최대 셋을 상대로, 그리고 무작위 태스크 집합 3,000개를 상대로 유지됩니다. +- 측정한 두 경우를 재현합니다(90 % 양보에서 10 %와 55 %, 태스크 셋일 때 예전 규칙에서 양보하는 태스크 뒤의 태스크가 5 %). + +이는 한정된 모델(태스크 최대 6개)에서의 탐색이며 **증명이 아닙니다**. 규칙을 일부러 망가뜨린 아홉 가지는 각각 호스트 테스트를 적어도 하나 실패시킵니다. 커널 연결을 일부러 망가뜨리면 부팅 테스트는 예전 규칙, `YIELD`가 잘못된 진입 종류를 넘기는 경우, 블록이 잘못된 진입 종류를 넘기는 경우에서 실패합니다. 틱 자신의 전환이 `Between`을 넘기는 경우, idle 루프가 틱에 대해 잘못 보고하는 경우, `handoff`의 잘못된 진입 종류는 부팅 테스트가 잡지 못합니다. 이런 실수는 태스크의 몫이 아니라 끊기기 전까지 실행하는 시간을 바꾸며, 호스트 모델은 이 경우들에서 규칙을 다룰 뿐 커널이 규칙을 쓰는 방식은 다루지 않습니다. + +QEMU에서 변경 뒤에 측정하니, 주기의 90 %에서 양보하는 공격 태스크 곁에서 다른 태스크가 CPU의 53.8 %부터 54.9 %를 가졌습니다(세 번 실행). 태스크 셋일 때는 어느 태스크도 29.7 % 아래로 내려가지 않았습니다. 양보 대신 틱 직전에 타임아웃 대기를 시작하는 공격 태스크 곁에서는 다른 태스크가 56.5 %를 가졌습니다. 모든 실행은 QEMU(TCG와 HVF)에서 했고 하드웨어에서는 실행하지 않았으며, 양보 지점은 공격 태스크를 위해 정했으므로 공격 태스크가 스스로 그 지점을 찾는 데 무엇이 필요한지는 측정하지 않았습니다. ## 알려진 공백 > [!NOTE] > 우선순위와 CPU 예산은 아직 없습니다. 코어는 하나뿐입니다. -- **스케줄링**: 1초 고정 슬라이스의 단순 라운드 로빈입니다. untyped 메모리를 가진 태스크는 태스크를 많이 만들어 모두의 몫을 희석시킬 수 있습니다. +- **스케줄링**: 틱 1초와 슬라이스 규칙을 쓰는 라운드 로빈입니다. 우선순위도 CPU 예산도 없으므로 CPU를 계속 쓰는 태스크는 자기 차례를 전부 쓰며 이를 막는 것이 없습니다. untyped 메모리를 가진 태스크는 여전히 태스크를 많이 만들어 모두의 몫을 희석시킬 수 있습니다. +- **타이밍 채널**: 열려 있습니다. 태스크는 양보하거나 블록할 시점을 골라 다른 태스크가 언제, 그리고 이제는 얼마나 오래 실행되는지를 여전히 바꿀 수 있습니다. 분석하지 않았습니다. 막으려면 고정된 시간 분할이 필요한데 K0에는 없습니다. +- **지연**: 실시간이나 지연에 대한 약속은 없습니다. 틱은 1초이고 커널은 선점되지 않습니다. +- **슬라이스 규칙 검증**: 호스트 모델은 규칙을 다룰 뿐 커널이 규칙을 쓰는 방식은 다루지 않으며([테스트 방법](#테스트-방법) 참고), 측정은 양보 지점을 공격 태스크를 위해 정한 QEMU에서만 했습니다. - **타임아웃**: 태스크가 준비되는 시점을 정할 뿐 실행되는 시점을 정하지 않습니다. 호출마다 선택하는 것이므로 타임아웃 없이 기다리는 태스크는 영원히 기다릴 수 있습니다. - **idle 상태**: 있지만, 루트 태스크가 자가 테스트 뒤에 `YIELD`를 계속 호출하는 동안에는 CPU가 잠들지 않습니다. 준비된 태스크도 기한이 있는 대기자도 없으면 머신은 idle 상태로 남고 어떤 것도 태스크를 깨울 수 없습니다. - **가용성**: 타임아웃 없이 블록하는 태스크는 격리 태스크를 포함해 상대방이 동작하지 않으면 계속 블록된 채로 남을 수 있습니다(GHSA-q99x-2wrv-358p). 커널은 선점되지 않으므로 객체가 많은 untyped에 대한 `CAP_REVOKE` 같은 긴 시스템 콜은 다른 모든 태스크와 모든 타임아웃을 지연시킵니다. 태스크 격리는 가용성을 다루지 않습니다. diff --git a/design/kr/terminal_KR.md b/design/kr/terminal_KR.md index ac0515d..f8c6fa6 100644 --- a/design/kr/terminal_KR.md +++ b/design/kr/terminal_KR.md @@ -137,7 +137,7 @@ QEMU는 시리얼 포트를 사용자의 터미널에 연결합니다. `cargo ru ## 테스트 방법 -**호스트 테스트**(`tools/host-test.sh`): `k0-conin`은 가짜 UART로 15개, `k0-term`은 vault feature가 있으면 24개, 없으면 21개, `k0-vault`는 Ed25519가 있으면 20개, 없으면 11개입니다. 전체는 ARM 호스트에서 354개, 다른 호스트에서 268개입니다. +**호스트 테스트**(`tools/host-test.sh`): `k0-conin`은 가짜 UART로 15개, `k0-term`은 vault feature가 있으면 24개, 없으면 21개, `k0-vault`는 Ed25519가 있으면 20개, 없으면 11개입니다. 전체는 ARM 호스트에서 363개, 다른 호스트에서 277개입니다(`k0-slice`가 9개를 더합니다). **부팅 매트릭스**: 새 행은 `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행입니다. @@ -153,7 +153,7 @@ QEMU는 시리얼 포트를 사용자의 터미널에 연결합니다. `cargo ru - **인증 없음**: 시리얼 선은 그 선에 닿을 수 있는 사람만큼만 신뢰할 수 있습니다. 운영자는 키를 지울 수 있지만(설계상의 서비스 거부) 서명을 얻지 못하고 정책을 바꿀 수 없습니다. - **외부가 구동하는 커널 코드**: 수신 코드는 EL1에서 실행됩니다. - **분석하지 않은 타이밍 채널**: 외부 당사자가 이제 태스크가 실행되는 동안 인터럽트를 일으킬 수 있습니다(읽는 쪽이 정한 한계 안에서). 읽는 쪽은 틱보다 세밀한 도착 시각을 알게 되고, 다른 태스크는 빼앗긴 시간을 알아챌 수 있습니다. -- **지연**: 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 준비된 태스크마다 최대 한 틱씩 지연됩니다. +- **지연**: 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 준비된 태스크마다 최대 한 틱씩 지연되며, 실행 중인 태스크가 두 틱 사이에 CPU를 받았다면 한 틱이 더해집니다([scheduling_KR.md](scheduling_KR.md) 참고). - **16550 콘솔에는 입력 없음**: 16550 콘솔에는 출력만 있고 입력은 없습니다. - **폭주 중 측정 없음**: 어떤 테스트도 머신에서 폭주 중 커널 시간을 측정하지 않습니다. 한계는 게이트로 논증하고 호스트 테스트로 보였습니다. - **프롬프트 전에 버림**: UART에 도착한 바이트를 센 것입니다. 바이트를 붙잡고 있는 에뮬레이터나 어댑터는 나중에 전달합니다(QEMU가 그렇습니다). diff --git a/design/kr/uefi_KR.md b/design/kr/uefi_KR.md index 0a7b698..3c4b128 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 호스트에서 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개를 실행합니다. +- **호스트 테스트 스크립트**: `tools/host-test.sh`는 이제 ARM 호스트에서 363개(`k0-abi` 15, `k0-cap` 44, `k0-boot` 85, `k0-efi` 33, `k0-conin` 15, `k0-slice` 9, Ed25519 포함 20개와 제외 11개의 `k0-vault`, 볼트 feature 포함 24개와 제외 21개의 `k0-term`, 두 그래뉼 각각에 `k0-mm` 43)를, `k0-mm` 테스트를 건너뛰는 그 밖의 호스트에서 277개를 실행합니다. - **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)에 있습니다. diff --git a/design/kr/vault_KR.md b/design/kr/vault_KR.md index 4e6ca65..15431ce 100644 --- a/design/kr/vault_KR.md +++ b/design/kr/vault_KR.md @@ -156,7 +156,7 @@ $ cargo build -p k0-kernel --features console,vault-ed25519 - 항상: `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 호스트에서 354개, 그 외 호스트에서 268개입니다(`k0-mm` 제외). +다른 크레이트와 합치면 호스트 테스트는 ARM 호스트에서 363개, 그 외 호스트에서 277개입니다(`k0-mm` 제외). 이 가운데 9개는 `k0-slice`의 테스트입니다. **루트 태스크 자가 테스트**(`userspace/root-task/src/oracle.rs`의 `test_oracle`, `vault`로 빌드한 이미지에만 있음). 다음을 검사합니다. @@ -183,7 +183,7 @@ $ cargo build -p k0-kernel --features console,vault-ed25519 - **키 하나**: 영속성, 키 가져오기·내보내기, DRBG, 양자 내성 알고리즘이 아직 없습니다. 새 키를 만들려면 재부팅해야 합니다. - **서비스 모드에 서명 클라이언트 없음**: 서비스 볼트의 키는 만들어지고 표시되지만 아직 다른 태스크가 쓰지 않습니다. 클라이언트 서명은 자가 테스트가 보여 줍니다. - **터미널과 볼트는 죽어도 다시 시작하지 않습니다**: 죽으면 그대로 멈춥니다. 루트 태스크는 신뢰 대상입니다. -- **가용성은 보호되지 않습니다**: 클라이언트는 엔드포인트 하나를 공유하며 모든 호출에 타임아웃을 써야 합니다([ipc_KR.md](ipc_KR.md) 참고). +- **가용성은 보호되지 않습니다**: 클라이언트는 엔드포인트 하나를 공유하며 모든 호출에 타임아웃을 써야 합니다([ipc_KR.md](ipc_KR.md) 참고). CPU를 계속 쓰는 태스크 하나 뒤에서는 호출자와 볼트가 왕복 한 번에 스케줄러 모델에서 4틱을 쓰며, 이전에는 2틱이었습니다. 터미널의 호출은 5틱 타임아웃을 쓰고, 고정 이미지의 서비스 모드에는 CPU를 계속 쓰는 태스크가 없습니다. - **루트 태스크는 신뢰 대상입니다**: 볼트를 만들고 읽을 수 있습니다. - **클라이언트 신원 없음**: 모든 signer가 키 하나를 공유합니다. - **엔트로피**: 시드는 입력만큼만 좋습니다. 키는 승인된 난수 비트 생성기에서 나오지 않습니다. diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index 40d6344..f28bdb6 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -149,8 +149,13 @@ extern "C" fn k0_fault(ctx: &mut Context, esr: u64, far: u64) { /// 타이머 틱의 선점 정책 함수입니다. (k0-arch가 EL0 IRQ 경로에서 링크 /// 계약으로 호출) /// -/// 기한이 지난 IPC 대기자를 먼저 깨운 뒤 다음 태스크로 돌립니다. 틱은 실행 -/// 중인 태스크를 끊고 들어왔으므로 현재 태스크는 기한 목록에 없습니다. +/// 기한이 지난 IPC 대기자를 먼저 깨운 뒤 현재 태스크를 끊을지 판정합니다. 틱은 +/// 실행 중인 태스크를 끊고 들어왔으므로 현재 태스크는 기한 목록에 없습니다. +/// +/// 틱이 언제나 다음 태스크로 돌리는 것은 아닙니다. 틱과 틱 사이에 CPU를 받은 +/// 태스크는 처음 맞는 틱 하나를 넘깁니다(`k0_sched::on_tick`). 그래서 틱 +/// 직전에 양보하거나 블록하는 태스크가 뒤에 선 태스크에게 주기의 끝자락만 주는 +/// 일이 없고, CPU를 받은 태스크는 온전한 한 주기 전에는 끊기지 않습니다. #[unsafe(no_mangle)] extern "C" fn k0_preempt() { // SAFETY: 벡터가 사용자 컨텍스트 저장을 마친 EL0 IRQ/FIQ 컨텍스트임 @@ -159,7 +164,7 @@ extern "C" fn k0_preempt() { #[cfg(feature = "console-input")] k0_ipc::console::wake(None); k0_ipc::expire_timeouts(k0_arch::irq::ticks(), None); - k0_sched::rotate(); + k0_sched::on_tick(); } } @@ -240,6 +245,11 @@ fn ipc_or_idle(ctx: &mut Context, switched: bool) -> Option { /// 건 대기자도 입력을 기다리는 태스크도 없으면 이 함수는 돌아오지 /// 않습니다(틱은 계속 처리함). /// +/// 깨어난 태스크가 틱에서 깨어났는지 틱 사이에 깨어났는지를 스케줄러에 알려 +/// 줍니다. 틱에서 깨어난 태스크는 주기의 처음에 들어오므로 다음 틱에서 끊길 수 +/// 있고, 콘솔 입력으로 틱 사이에 깨어난 태스크는 처음 맞는 틱 하나를 넘깁니다. +/// 기다리는 동안 틱과 입력이 함께 왔으면 틱으로 봅니다. +/// /// # Arguments /// `ctx` - 이번 진입을 일으킨 태스크(스케줄러의 현재 태스크)의 컨텍스트 fn idle_until_ready(ctx: &mut Context) { @@ -266,13 +276,15 @@ fn idle_until_ready(ctx: &mut Context) { // ctx는 현재 태스크의 컨텍스트이며, 기한이 지난 현재 태스크의 // 반환값은 이 참조로만 기록됨 unsafe { + let before = k0_arch::irq::ticks(); k0_arch::irq::wait_for_interrupt(); // 방금의 인터럽트가 입력을 가져왔으면 기다리는 태스크를 깨움. // 대기자가 블록된 현재 태스크 자신일 수 있어 ctx를 넘김 #[cfg(feature = "console-input")] k0_ipc::console::wake(Some(&mut *ctx)); - k0_ipc::expire_timeouts(k0_arch::irq::ticks(), Some(&mut *ctx)); - if k0_sched::block_and_switch() { + let now = k0_arch::irq::ticks(); + k0_ipc::expire_timeouts(now, Some(&mut *ctx)); + if k0_sched::resume_from_idle(now != before) { return; } } diff --git a/tools/host-test.sh b/tools/host-test.sh index a629490..8bfb253 100755 --- a/tools/host-test.sh +++ b/tools/host-test.sh @@ -6,7 +6,7 @@ cd "$root" host="$(rustc -vV | sed -n 's/^host: //p')" -cargo test --offline --target "$host" -p k0-abi -p k0-cap -p k0-boot -p k0-efi -p k0-conin "$@" +cargo test --offline --target "$host" -p k0-abi -p k0-cap -p k0-boot -p k0-efi -p k0-conin -p k0-slice "$@" # 키 볼트: 알고리즘을 넣은 것과 뺀 것을 따로 돌림(feature가 다르면 다른 코드) cargo test --offline --target "$host" -p k0-vault --features ed25519 "$@" cargo test --offline --target "$host" -p k0-vault "$@" diff --git a/tools/qemu-boot-test.sh b/tools/qemu-boot-test.sh index c3fb6f5..2c89dde 100755 --- a/tools/qemu-boot-test.sh +++ b/tools/qemu-boot-test.sh @@ -172,7 +172,7 @@ else reuse_sed='' fi -markers="k0: entry phase 1 (pre-MMU)|k0: dtb = |k0: mmu on (identity + fixed image address)|k0: jumping to higher half|k0: higher half (pc = |k0: w^x checks pass|k0: memory |k0: platform |k0: root task integrity ok|k0: entropy dtb=|k0: pac=|k0: irq on (timer 1s)|k0: kernel table pool |k0: root task loaded|k0: kernel reserve |k0: untyped |k0: root cnode ready|k0: bootinfo page ready|k0: user w^x checks pass|k0: dtb seeds wiped |k0: entering root task (el0)|root: hello from EL0|root: boot seed from rng-seed bytes |root: control byte filter [?]|root: retype/map tests pass|root: capability tests pass|root: untyped reuse test pass|root: child exit test pass|root: ipc tests pass|k0: task fault dabort-lower|k0: task fault fp-simd|root: fault isolation tests pass|root: preempt test pass|root: secret at |root: confined task reported|k0: task fault dabort-lower|root: isolation tests pass|k0: task fault dabort-lower|k0: task fault iabort-lower|k0: task fault dabort-lower|k0: unknown syscall 65535, killing task|root: violation tests pass|root: teardown tests pass|k0: idle (waiting for a timeout)|root: timeout tests pass|root: revocation tests pass|root: kernel reserve tests pass|root: sched tests pass|k0: tick " +markers="k0: entry phase 1 (pre-MMU)|k0: dtb = |k0: mmu on (identity + fixed image address)|k0: jumping to higher half|k0: higher half (pc = |k0: w^x checks pass|k0: memory |k0: platform |k0: root task integrity ok|k0: entropy dtb=|k0: pac=|k0: irq on (timer 1s)|k0: kernel table pool |k0: root task loaded|k0: kernel reserve |k0: untyped |k0: root cnode ready|k0: bootinfo page ready|k0: user w^x checks pass|k0: dtb seeds wiped |k0: entering root task (el0)|root: hello from EL0|root: boot seed from rng-seed bytes |root: control byte filter [?]|root: retype/map tests pass|root: capability tests pass|root: untyped reuse test pass|root: child exit test pass|root: ipc tests pass|k0: task fault dabort-lower|k0: task fault fp-simd|root: fault isolation tests pass|root: slice test yield pass|root: slice test block pass|root: preempt test pass|root: secret at |root: confined task reported|k0: task fault dabort-lower|root: isolation tests pass|k0: task fault dabort-lower|k0: task fault iabort-lower|k0: task fault dabort-lower|k0: unknown syscall 65535, killing task|root: violation tests pass|root: teardown tests pass|k0: idle (waiting for a timeout)|root: timeout tests pass|root: revocation tests pass|root: kernel reserve tests pass|root: sched tests pass|k0: tick " # 메모리의 로그에는 처음 몇 번의 틱만 남습니다. 자가 검증이 그보다 오래 걸리는 # 호스트에서는 끝의 틱이 로그에 없을 수 있으므로 순서 목록에서는 빼고, 첫 틱이 # 기록됐는지와(아래) 자가 검증 뒤에도 틱이 이어지는지를(위의 대기) 따로 봅니다. diff --git a/userspace/root-task/src/main.rs b/userspace/root-task/src/main.rs index c98a29c..a6abd2d 100644 --- a/userspace/root-task/src/main.rs +++ b/userspace/root-task/src/main.rs @@ -40,6 +40,7 @@ use core::sync::atomic::{AtomicU64, Ordering}; mod oracle; #[cfg(feature = "terminal")] mod service; +mod timeslice; use k0_abi::bootinfo::slot; use k0_abi::{bootinfo, err, ipc, obj, perm, rights, syscall}; @@ -88,8 +89,7 @@ static REUSE_BASE: AtomicU64 = AtomicU64::new(0); // 격리 태스크에 내줄 다음 스택 자리 번호 static NEXT_STACK: AtomicU64 = AtomicU64::new(0); -// 두 자식 태스크와 공유하는 진행 카운터 (같은 주소 공간) -static BUSY_COUNTER: AtomicU64 = AtomicU64::new(0); +// 자식 태스크와 공유하는 진행 카운터 (같은 주소 공간) static EXIT_COUNTER: AtomicU64 = AtomicU64::new(0); // IPC 서버·클라이언트 태스크와 공유하는 검증 상태 (같은 주소 공간) @@ -236,6 +236,23 @@ fn alloc_slot() -> u64 { s } +/// 검증 하나가 받은 슬롯을 전부 비우고 돌려주는 함수입니다. +/// +/// `first`부터 지금까지 내준 슬롯의 케이퍼빌리티를 모두 지우고(이미 빈 슬롯은 +/// 건너뜀) 할당 위치를 `first`로 되돌립니다. 그 슬롯의 오브젝트를 더 쓰지 않는 +/// 검증의 끝에서만 부릅니다. 루트 CNode의 슬롯은 뒤에 오는 검증들이 거의 다 +/// 쓰므로, 끝난 검증이 슬롯을 차지한 채로 두지 않습니다. +/// +/// # Arguments +/// `first` - 그 검증이 시작할 때의 할당 위치 +fn release_slots(first: u64) { + for s in first..NEXT_SLOT.load(Ordering::Relaxed) { + let r = cap_delete(s as i64); + check("release slot", r == 0 || r == err::BAD_SLOT); + } + NEXT_SLOT.store(first, Ordering::Relaxed); +} + fn retype_at(ut: u64, kind: u64, dest: u64) -> i64 { sys(syscall::RETYPE, [ut, kind, dest, 0, 0, 0]) as i64 } @@ -381,13 +398,6 @@ extern "C" fn child_exit_entry() -> ! { } } -/// 양보 없이 계속 도는 선점 검증용 자식 태스크의 진입점입니다. -extern "C" fn child_busy_entry() -> ! { - loop { - BUSY_COUNTER.fetch_add(1, Ordering::Relaxed); - } -} - /// 수신한 메시지를 기록하고 변환 응답을 돌려주는 IPC 서버 태스크의 /// 진입점입니다. SRV_DIE가 서면 응답 없이 종료해 NO_REPLY 경로를, /// SRV_HOLD가 서면 응답 자격을 쥔 채 일반 RECV로 넘어가 자격 덮어쓰기 @@ -1372,54 +1382,54 @@ fn test_reuse(b: &Boot) { fn test_sched_ipc_fault(b: &Boot) { let (ut, fs) = (b.ut_main, b.frame_size); let f = slot::CONSOLE as i64; + // 이 검증이 받는 슬롯은 끝에서 전부 돌려줌 + let first_slot = NEXT_SLOT.load(Ordering::Relaxed); - // 자식 스택 배치: +3, +5 그래뉼은 스택 가드로 비워 둠 - let s1 = retype(ut, obj::FRAME); - check("retype stack 1", s1 > 0); - check("map stack 1", map(s1, TEST_VA + 4 * fs, perm::RW) == 0); + // 자식 스택 배치: +5 그래뉼은 스택 가드로 비워 둠 let s2 = retype(ut, obj::FRAME); check("retype stack 2", s2 > 0); check("map stack 2", map(s2, TEST_VA + 6 * fs, perm::RW) == 0); - let sp_busy = TEST_VA + 5 * fs; let sp_exit = TEST_VA + 7 * fs; - let tcb_busy = retype(ut, obj::TCB); - check("retype tcb busy", tcb_busy > 0); + // 구성하지 않고 거부 경로 확인에만 쓰는 TCB + let tcb_spare = retype(ut, obj::TCB); + check("retype tcb spare", tcb_spare > 0); let tcb_exit = retype(ut, obj::TCB); check("retype tcb exit", tcb_exit > 0); - let entry_busy = child_busy_entry as usize as u64; let entry_exit = child_exit_entry as usize as u64; let (aspace, cnode) = (slot::ADDR_SPACE as i64, slot::CNODE as i64); // 거부 경로: 구성 전 재개, 잘못된 케이퍼빌리티, 스택 정렬 위반 - check("resume unconfigured", tcb_resume(tcb_busy) == err::BAD_STATE); + check("resume unconfigured", tcb_resume(tcb_spare) == err::BAD_STATE); check( "configure bad tcb", - tcb_configure(f, entry_busy, sp_busy, aspace, cnode, 0) == err::BAD_CAP, + tcb_configure(f, entry_exit, sp_exit, aspace, cnode, 0) == err::BAD_CAP, ); check( "configure bad aspace", - tcb_configure(tcb_busy, entry_busy, sp_busy, cnode, cnode, 0) == err::BAD_CAP, + tcb_configure(tcb_spare, entry_exit, sp_exit, cnode, cnode, 0) == err::BAD_CAP, ); check( "configure bad cnode", - tcb_configure(tcb_busy, entry_busy, sp_busy, aspace, aspace, 0) == err::BAD_CAP, + tcb_configure(tcb_spare, entry_exit, sp_exit, aspace, aspace, 0) == err::BAD_CAP, ); check( "configure empty cnode slot", - tcb_configure(tcb_busy, entry_busy, sp_busy, aspace, 9999, 0) == err::BAD_SLOT, + tcb_configure(tcb_spare, entry_exit, sp_exit, aspace, 9999, 0) == err::BAD_SLOT, ); check( "configure bad stack", - thread_configure(tcb_busy, entry_busy, sp_busy - 8) == err::BAD_VA, + thread_configure(tcb_spare, entry_exit, sp_exit - 8) == err::BAD_VA, ); // 거부된 구성은 TCB를 건드리지 않았어야 함 - check("still unconfigured", tcb_resume(tcb_busy) == err::BAD_STATE); + check("still unconfigured", tcb_resume(tcb_spare) == err::BAD_STATE); // 실행 중인 자신의 TCB는 재구성할 수 없음 check( "configure self", - thread_configure(slot::TCB as i64, entry_busy, sp_busy) == err::BAD_STATE, + thread_configure(slot::TCB as i64, entry_exit, sp_exit) == err::BAD_STATE, ); + // 구성된 적 없는 TCB도 삭제할 수 있음 + check("delete unconfigured tcb", cap_delete(tcb_spare) == 0); // 유한 태스크: 실행 -> 목표 도달 -> EXIT -> 루트로 복귀 check( @@ -1649,23 +1659,13 @@ fn test_sched_ipc_fault(b: &Boot) { check("deleted tcb gone", tcb_resume(tcb_fault) == err::BAD_SLOT); put_str("root: fault isolation tests pass\n"); - // 무한 태스크: 양보 없이 돌아도 타이머 선점으로 루트가 복귀해야 함. - // 확인 뒤에는 TCB를 삭제해 실행 중이던(준비 큐의) 태스크를 없앰 - check( - "configure tcb busy", - thread_configure(tcb_busy, entry_busy, sp_busy) == 0, - ); - check("resume tcb busy", tcb_resume(tcb_busy) == 0); - while BUSY_COUNTER.load(Ordering::Relaxed) == 0 { - yield_now(); - } - put_str("root: preempt test pass\n"); - check("delete ready tcb", cap_delete(tcb_busy) == 0); - let seen = BUSY_COUNTER.load(Ordering::Relaxed); - for _ in 0..4 { - yield_now(); - } - check("deleted task stopped", BUSY_COUNTER.load(Ordering::Relaxed) == seen); + // 양보 없이 도는 태스크가 타이머에 끊기는지, 그리고 틱 사이에 CPU를 받은 + // 태스크가 처음 맞는 틱을 넘기는지. 앞선 검증의 태스크는 모두 종료됐으므로 + // 준비 큐에는 루트뿐임(이 검증의 전제) + timeslice::test(b); + + // 여기서 만든 태스크는 모두 끝났고 엔드포인트와 스택도 더 쓰지 않음 + release_slots(first_slot); } /// 격리된 태스크 하나를 만드는 데 필요한 케이퍼빌리티 묶음 구조체입니다. diff --git a/userspace/root-task/src/timeslice.rs b/userspace/root-task/src/timeslice.rs new file mode 100644 index 0000000..6eb2754 --- /dev/null +++ b/userspace/root-task/src/timeslice.rs @@ -0,0 +1,209 @@ +//! 타이머 선점과, 틱 사이에 CPU를 받은 태스크가 처음 맞는 틱에서 끊기지 않는지를 +//! 보는 자가 검증 모듈입니다. +//! +//! # Features +//! 커널은 틱과 틱 사이에 CPU를 받은 태스크에게 처음 맞는 틱 하나를 넘기게 합니다. +//! 그렇지 않으면 틱 직전에 양보하거나 블록하는 태스크가 뒤에 선 태스크에게 주기의 +//! 끝자락만 주고 다음 주기를 통째로 다시 받습니다. 이 모듈은 그 규칙이 양보 +//! 경로와 블록 경로 양쪽에서 지켜지는지 확인합니다. +//! +//! EL0에는 시계가 없으므로 시간을 재지 않고 실행 순서만으로 판정합니다. 태스크 +//! 넷을 씁니다. 넘겨주는 태스크, 넘겨받아 끝없이 도는 태스크, 처음 실행될 때 +//! 표지를 남기는 태스크, 그리고 준비 단계의 도우미입니다. 루트가 틱 하나짜리 +//! 기한 대기에 들어가면 준비 큐의 순서는 넘겨주는 태스크, 도는 태스크, 표지 +//! 태스크가 됩니다. 넘겨주는 태스크는 곧바로 양보하거나(양보 경로) 블록하므로 +//! (블록 경로) 도는 태스크는 틱 사이에 CPU를 받습니다. +//! +//! - 규칙이 지켜지면 도는 태스크는 첫 틱을 넘기고, 루트의 기한인 둘째 틱에서야 +//! 끊깁니다. 그 틱에서 루트는 준비 큐에서 도는 태스크보다 앞에 서므로, 루트가 +//! 다시 실행될 때까지 도는 태스크는 표지를 볼 수 없습니다. +//! - 규칙이 없으면 도는 태스크는 첫 틱에서 끊기고, 표지 태스크가 실행된 뒤에 +//! 다시 돌면서 표지를 봅니다. 루트는 그 뒤인 둘째 틱에서야 깨어납니다. +//! +//! 루트가 깨어났다는 사실 자체가 양보하지 않는 태스크도 타이머에 끊긴다는 것을 +//! 보여 줍니다(도는 태스크는 CPU를 스스로 내놓지 않음). +//! +//! 준비 단계에 틱이 끼어들어도 판정이 흔들리지 않게, 루트는 먼저 도우미에게 +//! 양보했다가 도우미가 블록할 때 CPU를 돌려받습니다. 그러면 루트 자신이 틱 +//! 사이에 들어온 태스크가 되어, 태스크 셋을 준비 큐에 넣고 대기에 들어가기까지의 +//! 시스템 콜 네 개 사이에 온 틱 하나는 루트를 끊지 못합니다. 그 구간에 틱이 둘 +//! 오려면 호스트가 그 사이에 1초 넘게 멈춰야 합니다. +//! +//! 판정은 기한의 계산에 기대고 있습니다. 틱 하나짜리 대기는 그때의 틱 수에 2를 +//! 더한 틱에서 끝납니다(k0-ipc의 `deadline_of`). 루트가 대기에 들어가는 순간에 +//! 틱이 이미 걸려 있던 드문 경우에는 규칙이 없는 커널도 통과할 수 있습니다(그 +//! 틱이 넘겨주는 태스크의 면제를 쓰는 대신 기한은 한 틱 이르게 잡히므로). 규칙이 +//! 있는 커널이 실패하는 틱 배치는 위의 1초 넘는 멈춤뿐입니다. +//! +//! 이 검증은 시작할 때 준비 큐에 다른 태스크가 없어야 합니다. 앞선 검증의 +//! 태스크가 모두 종료된 자리에서만 부릅니다. 끝나면 만든 케이퍼빌리티를 전부 +//! 지우고 받은 슬롯을 돌려줍니다. + +use core::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +use super::{ + alloc_slot, cap_delete, check, fail, put_str, recv, release_slots, retype, retype_at, + tcb_resume, yield_now, Boot, NEXT_SLOT, TEST_VA, +}; +use k0_abi::{err, ipc, obj, perm}; + +/// 표지 태스크가 실행됐으면 1 +static MARK: AtomicU64 = AtomicU64::new(0); +/// 도는 태스크가 표지를 본 적이 있으면 1 +static SAW: AtomicU64 = AtomicU64::new(0); +/// 도는 태스크의 진행(삭제된 뒤에 멈췄는지 보는 데 씀) +static SPINS: AtomicU64 = AtomicU64::new(0); +/// 아무도 보내지 않는 엔드포인트의 슬롯. 태스크들이 여기서 기한 없이 블록됨 +static PARK: AtomicU64 = AtomicU64::new(0); + +const BY_YIELD: u64 = 1; +const BY_BLOCK: u64 = 0; + +/// 태스크 스택이 놓이는 첫 그래뉼 번호(TEST_VA 기준). 사이사이는 가드로 비워 둠 +const STACK_BASE: u64 = 50; + +/// 아무도 보내지 않는 엔드포인트에서 블록되는 함수입니다. 루트가 이 태스크를 +/// 삭제할 때까지 돌아오지 않습니다. +fn park() -> ! { + let _ = recv(PARK.load(Relaxed) as i64, 0); + loop { + yield_now(); + } +} + +/// 다음 태스크에게 CPU를 넘겨주는 태스크의 진입점입니다. +/// +/// # Arguments +/// `mode` - [BY_YIELD]면 먼저 양보하고, [BY_BLOCK]이면 곧바로 블록함 +extern "C" fn giver_entry(mode: u64) -> ! { + if mode == BY_YIELD { + yield_now(); + } + park() +} + +/// 양보하지 않고 끝없이 도는 태스크의 진입점입니다. 표지를 보면 기록합니다. +extern "C" fn runner_entry(_arg: u64) -> ! { + loop { + SPINS.fetch_add(1, Relaxed); + if MARK.load(Relaxed) != 0 { + SAW.store(1, Relaxed); + } + } +} + +/// 처음 실행될 때 표지를 남기고 블록되는 태스크의 진입점입니다. +extern "C" fn marker_entry(_arg: u64) -> ! { + MARK.store(1, Relaxed); + park() +} + +/// 곧바로 블록되는 도우미 태스크의 진입점입니다. +extern "C" fn helper_entry(_arg: u64) -> ! { + park() +} + +/// 검증이 쓰는 슬롯과 스택 묶음 구조체입니다. 두 경로가 같은 슬롯을 다시 씁니다. +struct Stage { + ut: u64, + /// 루트가 기한 대기를 거는 엔드포인트 + wait: i64, + /// 넘겨주는 태스크, 도는 태스크, 표지 태스크, 도우미의 TCB 슬롯과 스택 최상단 + tcb: [u64; 4], + sp: [u64; 4], +} + +/// 한 경로를 검증하는 함수입니다. 도는 태스크가 첫 틱을 넘겼으면 true +/// +/// # Arguments +/// `st` - 슬롯과 스택 +/// `mode` - [BY_YIELD] 또는 [BY_BLOCK] +fn one(st: &Stage, mode: u64) -> bool { + MARK.store(0, Relaxed); + SAW.store(0, Relaxed); + let entries = [ + (giver_entry as usize as u64, mode), + (runner_entry as usize as u64, 0), + (marker_entry as usize as u64, 0), + (helper_entry as usize as u64, 0), + ]; + for (i, (entry, arg)) in entries.into_iter().enumerate() { + check("slice tcb", retype_at(st.ut, obj::TCB, st.tcb[i]) == 0); + check( + "slice configure", + super::tcb_configure( + st.tcb[i] as i64, + entry, + st.sp[i], + k0_abi::bootinfo::slot::ADDR_SPACE as i64, + k0_abi::bootinfo::slot::CNODE as i64, + arg, + ) == 0, + ); + } + let [giver, runner, marker, helper] = st.tcb.map(|s| s as i64); + + // 루트를 틱 사이에 들어온 태스크로 만듦: 도우미가 블록하면서 CPU를 돌려줌 + check("slice resume helper", tcb_resume(helper) == 0); + yield_now(); + + check("slice resume giver", tcb_resume(giver) == 0); + check("slice resume runner", tcb_resume(runner) == 0); + check("slice resume marker", tcb_resume(marker) == 0); + check("slice wait", recv(st.wait, ipc::timeout(1)).status == err::TIMEOUT); + let (saw, marked) = (SAW.load(Relaxed), MARK.load(Relaxed)); + + // 도는 태스크는 준비 큐에 있음. 삭제하면 더 실행되지 않아야 함 + check("slice delete runner", cap_delete(runner) == 0); + let seen = SPINS.load(Relaxed); + check("slice delete giver", cap_delete(giver) == 0); + check("slice delete marker", cap_delete(marker) == 0); + check("slice delete helper", cap_delete(helper) == 0); + for _ in 0..4 { + yield_now(); + } + check("slice deleted runner stopped", seen != 0 && SPINS.load(Relaxed) == seen); + // 표지 태스크는 어느 커널에서든 루트보다 먼저 실행됨 + check("slice marker ran", marked == 1); + saw == 0 +} + +/// 타이머 선점과 틱 면제를 양보 경로와 블록 경로에서 검증하는 함수입니다. +/// +/// # Arguments +/// `b` - 부팅 때 찾은 untyped와 그래뉼 크기 +pub fn test(b: &Boot) { + let (ut, fs) = (b.ut_main, b.frame_size); + let first_slot = NEXT_SLOT.load(Relaxed); + let wait = retype(ut, obj::ENDPOINT); + let park = retype(ut, obj::ENDPOINT); + check("slice endpoints", wait > 0 && park > 0); + PARK.store(park as u64, Relaxed); + let mut st = Stage { + ut, + wait, + tcb: [0; 4], + sp: [0; 4], + }; + for i in 0..4 { + let frame = retype(ut, obj::FRAME); + let va = TEST_VA + (STACK_BASE + 2 * i as u64) * fs; + check("slice stack", frame > 0 && super::map(frame, va, perm::RW) == 0); + st.sp[i] = va + fs; + st.tcb[i] = alloc_slot(); + } + + if !one(&st, BY_YIELD) { + fail("slice: a task that got the cpu by a yield was cut at its first tick"); + } + put_str("root: slice test yield pass\n"); + if !one(&st, BY_BLOCK) { + fail("slice: a task that got the cpu by a block was cut at its first tick"); + } + put_str("root: slice test block pass\n"); + + // 태스크는 경로마다 지웠음. 스택(삭제가 매핑도 걷음)과 엔드포인트까지 지우고 + // 슬롯을 돌려줌 + release_slots(first_slot); + put_str("root: preempt test pass\n"); +}