diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4992b94..d128e0a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -92,11 +92,11 @@ $ 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-slice`, `k0-part`, `k0-vault` and `k0-term` on any host (415 tests on an AArch64 host, 327 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. `k0-part` has 36 tests: they run the scheduler's decisions under a time partition table on a model of the kernel, check the arithmetic of tick instants, and compare the Rust code with the recorded results of a Lean model (see "Changing the scheduler core" below). 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-part`, `k0-sup`, `k0-vault` and `k0-term` on any host (457 tests on an AArch64 host, 369 elsewhere). `k0-cap` has 71 tests, and 17 of them are about `UNTYPED_SPLIT`. `k0-sup` has 20 tests: they run the policy that supervises the terminal and the vault on a mock host. Three of them tie its log lines to the rest of the repository: one pins the wording that the documents quote, one checks that no line contains a word that `tools/qemu-boot-test.sh` reads as a failure, and one reads that word list from the script itself. So if you change `fail_re` in the script or the wording of a supervisor line, change the test and the documents with it. `k0-slice` has 9 tests: they run the rule that decides whether a tick cuts the running task on a model of the scheduler. `k0-part` has 36 tests: they run the scheduler's decisions under a time partition table on a model of the kernel, check the arithmetic of tick instants, and compare the Rust code with the recorded results of a Lean model (see "Changing the scheduler core" below). It runs `k0-vault` twice, with and without the algorithm feature `vault-ed25519`, which gives 22 and 13 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. 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`. After that come `root: partition refusal pass` and `root: partition window pass`, and `root: partition sealed` comes before `root: sched tests pass`. The time partition test lets a table of 9 ticks run one round, so it adds about 15 seconds to every boot. If the host stalls QEMU for more than a second during it, the test runs once more and the script reports `boot-test: partition window retries: 1` without failing. `tools/boot-matrix.sh` runs such a boot row again and fails it when the second run needed the retry too. 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`. `root: tcb status tests pass` comes after `root: fault isolation tests pass`, and `root: untyped split tests pass` comes between `root: timeout tests pass` and `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`. After that come `root: partition refusal pass` and `root: partition window pass`, and `root: partition sealed` comes before `root: sched tests pass`. The time partition test lets a table of 9 ticks run one round, so it adds about 15 seconds to every boot. If the host stalls QEMU for more than a second during it, the test runs once more and the script reports `boot-test: partition window retries: 1` without failing. `tools/boot-matrix.sh` runs such a boot row again and fails it when the second run needed the retry too. 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 82 rows in total on a Mac with HVF and 71 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. +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 82 rows in total on a Mac with HVF and 71 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. For a terminal image the boot test also expects `root: terminal restart test pass` before `root: service started`, and `root: vault restart test pass` before the seed line when a vault is built in. The session script fails when `root: ` appears in the output after the prompt, because the root task prints there only when a service ended. [USAGE.md](USAGE.md) describes the rows. The default QEMU CPU model (`cortex-a72`) has no PAC, PAN or RNDR. To exercise those paths as well, boot on QEMU's `max` model and require the matching log lines. Any arguments after the kernel path are passed to QEMU. You can enter it as follows: @@ -124,9 +124,10 @@ In the following table, you can see where each area is tested. | Area | Host unit tests | Boot self-tests in the root task | | --- | --- | --- | | `k0-abi` constants and shared layouts | yes | indirectly | -| `k0-cap` untyped bootstrap and retype | yes | yes | +| `k0-cap` untyped bootstrap, retype and split | yes | yes | | `k0-boot` DTB parser, PAC key derivation, root task image | yes, plus fuzzing | yes | | `k0-vault` request state machine, protocol, policy and provider boundary | yes, with and without `vault-ed25519` | yes, in images built with `vault`, through `test_oracle` and the `vault*` rows of the boot matrix | +| `k0-sup` policy that supervises the terminal and the vault | yes, with a mock host | partly, in images built with `terminal`: the restart path runs before the service starts, with one restart per service and without waits. The timed loop in service has no test | | `k0-efi` memory plan from the UEFI memory map, DTB rewrite, independent check, ACPI table reader and tree synthesis | yes, plus fuzzing | yes, through the `uefi-*` rows of the boot matrix | | `loader` (UEFI application: firmware calls, cache flush, MMU off, jump) | no | yes, through the `uefi-*` rows, plus the static check `tools/pe-check.py` | | `k0-mm` page tables and W^X attributes | yes, on AArch64 hosts | yes | diff --git a/CONTRIBUTING_KR.md b/CONTRIBUTING_KR.md index eaed06a..970bbfa 100644 --- a/CONTRIBUTING_KR.md +++ b/CONTRIBUTING_KR.md @@ -94,11 +94,11 @@ $ 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-slice`, `k0-part`, `k0-vault`, `k0-term`의 테스트를 어느 호스트에서나 실행합니다(AArch64 호스트에서 415개, 그 밖에서 327개). `k0-slice`는 9개이며, 틱이 실행 중인 태스크를 끊을지 정하는 규칙을 스케줄러 모델로 검사합니다. `k0-part`는 36개입니다. 시간 분할 표가 있을 때의 스케줄러 판정을 커널 모델 위에서 실행하고, 틱 시각의 산술을 검사하고, Rust 코드를 Lean 모델의 기록된 결과와 비교합니다(뒤의 "스케줄러 코어를 바꿀 때" 참고). `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-part`, `k0-sup`, `k0-vault`, `k0-term`의 테스트를 어느 호스트에서나 실행합니다(AArch64 호스트에서 457개, 그 밖에서 369개). `k0-cap`은 71개이고 그 가운데 17개가 `UNTYPED_SPLIT`에 관한 것입니다. `k0-sup`은 20개이며, 터미널과 볼트를 감독하는 정책을 모형 호스트 위에서 실행합니다. 그 가운데 셋은 로그 줄을 저장소의 나머지와 묶어 둡니다. 하나는 문서가 인용하는 문구를 고정하고, 하나는 어느 줄에도 `tools/qemu-boot-test.sh`가 실패로 읽는 낱말이 없는지 확인하고, 하나는 그 낱말 목록을 스크립트에서 직접 읽습니다. 그러니 스크립트의 `fail_re`나 감독자 줄의 문구를 바꾸면 테스트와 문서도 함께 바꾸세요. `k0-slice`는 9개이며, 틱이 실행 중인 태스크를 끊을지 정하는 규칙을 스케줄러 모델로 검사합니다. `k0-part`는 36개입니다. 시간 분할 표가 있을 때의 스케줄러 판정을 커널 모델 위에서 실행하고, 틱 시각의 산술을 검사하고, Rust 코드를 Lean 모델의 기록된 결과와 비교합니다(뒤의 "스케줄러 코어를 바꿀 때" 참고). `k0-vault`는 알고리즘 feature `vault-ed25519`를 포함한 경우와 포함하지 않은 경우로 두 번 실행하며, 각각 22개와 13개입니다. `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초 더 걸립니다. 시간 조각 테스트는 두 번(`YIELD`로 CPU를 받은 태스크, 기다림으로 받은 태스크) 실행해 합계 약 4초가 걸리며, 이를 대신한 이전 선점 테스트는 약 1초가 걸렸습니다. `root: preempt test pass`보다 앞에 `root: slice test yield pass`와 `root: slice test block pass`가 이 순서로 나오는 것도 기대합니다. 그 뒤에 `root: partition refusal pass`와 `root: partition window pass`가 나오고, `root: partition sealed`는 `root: sched tests pass`보다 앞에 나옵니다. 시간 분할 테스트는 9틱짜리 표를 한 바퀴 돌리므로 부팅마다 약 15초를 더합니다. 그 도중에 호스트가 QEMU를 1초 넘게 멈춰 세우면 테스트가 한 번 더 실행되고, 스크립트는 실패로 처리하지 않고 `boot-test: partition window retries: 1`을 보고합니다. `tools/boot-matrix.sh`는 그런 부팅 행을 다시 실행하고, 두 번째 실행에서도 재시도가 필요했으면 그 행을 실패로 처리합니다. 느린 환경에서는 `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`를 기대합니다. `root: tcb status tests pass`는 `root: fault isolation tests pass` 뒤에 나오고, `root: untyped split tests pass`는 `root: timeout tests pass`와 `root: revocation 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`가 이 순서로 나오는 것도 기대합니다. 그 뒤에 `root: partition refusal pass`와 `root: partition window pass`가 나오고, `root: partition sealed`는 `root: sched tests pass`보다 앞에 나옵니다. 시간 분할 테스트는 9틱짜리 표를 한 바퀴 돌리므로 부팅마다 약 15초를 더합니다. 그 도중에 호스트가 QEMU를 1초 넘게 멈춰 세우면 테스트가 한 번 더 실행되고, 스크립트는 실패로 처리하지 않고 `boot-test: partition window retries: 1`을 보고합니다. `tools/boot-matrix.sh`는 그런 부팅 행을 다시 실행하고, 두 번째 실행에서도 재시도가 필요했으면 그 행을 실패로 처리합니다. 느린 환경에서는 `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에서 82행, CI에서 71행입니다. 행 `input-*`와 `term-*`는 콘솔 입력과 터미널을 다룹니다. 터미널 이미지는 `k0: task fault` 줄이 두 개 더 나오며(볼트 없이 8개, 볼트와 함께 10개), `tools/term-test.py <이미지>`가 정해진 직렬 세션을 실행합니다. 행의 내용은 [USAGE_KR.md](USAGE_KR.md)에 있습니다. +서명 오라클이 있는 이미지(`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에서 82행, CI에서 71행입니다. 행 `input-*`와 `term-*`는 콘솔 입력과 터미널을 다룹니다. 터미널 이미지는 `k0: task fault` 줄이 두 개 더 나오며(볼트 없이 8개, 볼트와 함께 10개), `tools/term-test.py <이미지>`가 정해진 직렬 세션을 실행합니다. 터미널 이미지에서는 부팅 테스트가 `root: service started` 앞에 `root: terminal restart test pass`도 기대하고, 볼트가 빌드에 포함돼 있으면 시드에 관한 줄 앞에 `root: vault restart test pass`도 기대합니다. 세션 스크립트는 프롬프트 뒤의 출력에 `root: `가 나타나면 실패합니다. 루트 태스크는 서비스가 끝났을 때만 거기에 출력하기 때문입니다. 행의 내용은 [USAGE_KR.md](USAGE_KR.md)에 있습니다. 기본 QEMU CPU 모델(`cortex-a72`)에는 PAC, PAN, RNDR이 없습니다. 이 경로까지 검증하려면 QEMU의 `max` 모델로 부팅하고 해당 로그 줄을 필수로 지정하세요. 커널 경로 뒤의 인자는 그대로 QEMU에 전달됩니다. 다음과 같이 입력할 수 있습니다. @@ -126,9 +126,10 @@ $ tools/qemu-boot-test.sh target/aarch64-unknown-none-softfloat/debug/k0-kernel. | 영역 | 호스트 단위 테스트 | 루트 태스크의 부팅 자가 테스트 | | --- | --- | --- | | `k0-abi` 상수와 공유 레이아웃 | 있음 | 간접적으로 | -| `k0-cap` untyped 부트스트랩과 retype | 있음 | 있음 | +| `k0-cap` untyped 부트스트랩, retype, 분할 | 있음 | 있음 | | `k0-boot` DTB 파서, PAC 키 파생, 루트 태스크 이미지 | 있음, 퍼징 포함 | 있음 | | `k0-vault` 요청 상태 기계, 프로토콜, 정책, 프로바이더 경계 | 있음, `vault-ed25519` 포함과 미포함 | 있음, `vault`를 포함해 빌드한 이미지에서 `test_oracle`과 부팅 매트릭스의 `vault*` 행으로 | +| `k0-sup` 터미널과 볼트를 감독하는 정책 | 있음, 모형 호스트로 | 일부만, `terminal`을 포함해 빌드한 이미지에서. 재시작 경로는 서비스가 시작되기 전에 서비스마다 재시작 한 번으로, 대기 없이 실행됩니다. 서비스 중의 시간이 걸린 루프에는 테스트가 없습니다 | | `k0-efi` UEFI 메모리 맵에서의 메모리 계획, DTB 재작성, 독립 검증, ACPI 테이블 읽기와 트리 합성 | 있음, 퍼징 포함 | 있음, 부팅 매트릭스의 `uefi-*` 행으로 | | `loader` (UEFI 애플리케이션: 펌웨어 호출, 캐시 비우기, MMU 끄기, 점프) | 없음 | 있음, `uefi-*` 행과 정적 검사 `tools/pe-check.py`로 | | `k0-mm` 페이지 테이블과 W^X 속성 | AArch64 호스트에서 있음 | 있음 | diff --git a/Cargo.lock b/Cargo.lock index 7483765..6abe8da 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -211,6 +211,10 @@ dependencies = [ name = "k0-slice" version = "0.1.0" +[[package]] +name = "k0-sup" +version = "0.1.0" + [[package]] name = "k0-task" version = "0.1.0" @@ -266,6 +270,7 @@ name = "root-task" version = "0.1.0" dependencies = [ "k0-abi", + "k0-sup", "k0-term", "k0-vault", ] diff --git a/Cargo.toml b/Cargo.toml index 4b51950..dbb66c6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,7 @@ members = [ "userspace/root-task", "userspace/k0-vault", "userspace/k0-term", + "userspace/k0-sup", "loader", ] # UEFI 로더는 타겟이 달라(aarch64-unknown-uefi) 기본 빌드 대상에서 뺌. diff --git a/INTRODUCTION.md b/INTRODUCTION.md index fc554bc..7664f08 100644 --- a/INTRODUCTION.md +++ b/INTRODUCTION.md @@ -132,14 +132,15 @@ 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 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). +- **Memory budgets**: a smaller block can be cut out of a block of free memory (UNTYPED_SPLIT). The size is given in granules, and every object takes one granule. A task that is given only the smaller block can therefore make exactly that many objects and no more. Taking back the larger block removes the smaller one and everything made from it. This bounds how much memory a task has. It does not bound how long the kernel works for that task (see "How far the isolation goes"). +- **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). A program that holds the key to a task can ask the kernel whether that task has not started, is alive or has ended (TCB_STATUS). The kernel gives no reason for the end and tells nobody by itself. - **Time partitions**: every task belongs to one of 8 groups called domains. A timetable of up to 16 entries (the time partition table) says which domain may use the processor in which seconds, and it repeats. A domain runs only in its own windows of that table. When a domain has nothing to run in its window, the processor waits, and the time is not given to another domain. Before a tick at which the domain changes, the kernel takes the timer interrupt 25 ms early, does the switch and then waits for the instant of the tick. The next domain starts at that instant, to within the wait loop and the way out of the kernel, as long as the kernel work that was under way and the switch fit in the 25 ms. - **Who sets it**: one key that the root task gets at boot (the control capability `PartCtl`) allows setting the table (PART_SET_TABLE) and putting a task that has not run yet into a domain (PART_SET_DOMAIN). The key cannot be copied, and deleting it fixes the table and the domains until the next boot. - **Without a table**: there is one domain, and tasks take turns as described above. - **Not used by any image yet**: the root task tries the mechanism in a self-test at every boot and then deletes the key. Every image built today therefore runs with one domain. What the partitions do and do not protect against is in [SECURITY.md](SECURITY.md) and [design/en/scheduling.md](design/en/scheduling.md#time-partitions). - **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. +- **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 in service prints nothing there: its terminal waits for input, and its root task waits with a time limit between two looks at the services. - **Kernel tables sized at boot**: the kernel sets aside the memory for its own page tables and address space entries at boot, in proportion to the memory it hands out (about 0.4 % of RAM). So a task cannot use these tables up, and the number of address spaces is limited only by memory. - **Crash containment**: when a task crashes, makes a system call the kernel does not know, or exits, only that task is stopped (fault isolation). - **Task isolation and taking keys back**: tasks tied to different key rings and address spaces cannot reach each other's memory or keys. Every key remembers which key it was copied from (derivation list). Taking a key back (CAP_REVOKE) or deleting it (CAP_DELETE) has the following effects. @@ -167,13 +168,14 @@ These features only add and are not in `default`, so **every build command must ``` Under `cargo run`, QEMU's own escape key is Ctrl-A (Ctrl-A, then X quits QEMU), so Ctrl-A never reaches K0. - - **Start-up order**: a terminal image runs all self-tests first. Then the root task starts a new vault and hands it the boot seed (`root: vault seeded`), checks that two hostile tasks wired exactly like the terminal are refused and end in a fault (`root: terminal wiring holds`), drops its own admin capability and starts the terminal (`root: service started`). After that the banner `K0 operator console, type 'help'` and the prompt `k0> ` appear. On a machine without an input path, `root: no console input, terminal not started` appears and the terminal does not start. + - **Start-up order**: a terminal image runs all self-tests first. Then the root task tries out how it would start the vault again (`root: vault restart test pass`), starts a new vault and hands it the boot seed (`root: vault seeded`), checks that two hostile tasks wired exactly like the terminal are refused and end in a fault (`root: terminal wiring holds`, `root: terminal restart test pass`), drops its own admin capability and starts the terminal (`root: service started`). After that the banner `K0 operator console, type 'help'` and the prompt `k0> ` appear. On a machine without an input path, `root: no console input, terminal not started` appears and the terminal does not start. + - **Supervision**: after the start the root task keeps watching the terminal and the vault. Every second tick it asks the kernel whether the two tasks are still alive. When one has ended, the root task takes back the block of memory the task was built from and builds the task again in the same place, at most 3 times per service per boot and after waits of at least 2, 8 and 32 ticks. The memory of a vault that ended is erased first, and the vault that is started in its place has no key, because the boot seed was used once. So after a vault restart there is no key until the next boot. The lines the root task prints then, such as `root: vault started again without a key`, are listed in [USAGE.md](USAGE.md). - **Commands**: they are `help`, `vault status` (the vault's state), `vault pubkey` (the public key), `vault keygen ed25519` (make the key) and `vault zeroize confirm` (erase the key). `vault zeroize` alone erases nothing and answers `err confirm-required`. Every command ends with one line, `ok` or `err `. `vault status` always prints `validated=no`, because the implementation has no validation of any kind. [USAGE.md](USAGE.md) has the details and an example screen. - **Input rules**: a line ends with Enter (CR or LF), has at most 64 characters and takes printable ASCII only. Backspace and DEL erase one character, Ctrl-C and Ctrl-U cancel the line, and escape sequences such as the arrow keys are ignored. Bytes that reached the UART before the prompt are dropped. If input was lost, everything up to the next line end is dropped and `err input-lost` is printed. - **What the kernel does**: the kernel only collects the bytes received by the UART in a ring of 256 bytes and never interprets them. A task takes them one byte at a time with the system call `CONSOLE_READ`, and only one task can wait at a time. The receive interrupt stays off until a task first reads console input. At that moment one line `k0: tick lines off (console input in use)` is printed and the periodic `k0: tick N` lines stop, while the timer, preemption and timeouts keep working. When the ring is full, the kernel masks the receive interrupt itself and reopens it after the task has taken half of the ring, so a flood of input costs the kernel no more work than the reader allows. At boot the log says `k0: console input on (pl011 irq 33)` or `k0: console input off ()`. A wrong interrupt number switches off input only and does not stop the boot. - **There is no authentication**: whoever holds the serial line is the operator and can do all four of the operator's jobs (status, public key, make the key, erase the key). That includes erasing the key and so stopping the service, which is by design. The operator cannot get a signature and cannot change policy. - **Do not trust the screen**: if a kernel line appears while someone is typing, the line on the screen is split but the input buffer is whole, and Enter runs the whole buffer. Any task with console output can print lines that look like kernel or root task lines, so a line prefix proves nothing. The terminal can also erase within its own line (it prints backspace). - - **Known limits**: the terminal and the vault are not restarted if they die (the root task is trusted). In service mode no client asks for signatures yet, so the key is made and shown but not used by another task (the self-test shows client signing). Terminal output counts against the user share of the boot log, and once that share is full, later task output is not recorded there. + - **Known limits**: the root task that watches the terminal and the vault is trusted, and nothing watches the root task. It notices only a task that ended, up to two ticks late, and not a task that hangs. No test makes the real terminal or the real vault end while they are in service: the waits and the limit of 3 are tested on the build machine only, and each boot tries one restart per service, without waits. In service mode no client asks for signatures yet, so the key is made and shown but not used by another task (the self-test shows client signing). Terminal output counts against the user share of the boot log, and once that share is full, later task output is not recorded there. The root task tests every item above with self-tests on every boot. The signing oracle and the terminal are tested in the images built with them. @@ -278,7 +280,7 @@ What it does not stop: - 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, 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. A machine-checked proof exists for a model of one domain, not for the code and not for several domains. N grows with every task that is created. - The scheduler leaks timing between tasks of one domain. A task still changes when, and for how long, another task of its domain runs by choosing when to yield or block. This has not been analysed. Time partitions are the mechanism against this between domains, but no image puts tasks into more than one domain yet, and the mechanism has limits of its own (see [SECURITY.md](SECURITY.md)). 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. + - 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. Giving a task only a smaller block (UNTYPED_SPLIT) limits how much memory and how many objects it has. It does not limit how long such a call takes, because the time follows the number of keys that are removed, copies included. - 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 lines the kernel prints when a task ends (a crash, an exit, an unknown system call) share 4 KiB of the boot log and can no longer fill the kernel part. A task that can create tasks can still push such lines of other tasks out of the log. - 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. @@ -299,14 +301,14 @@ Missing features: - **The rest of input**: only input from the console UART exists (PL011 and SBSA UART, optional). Input from a 16550 console or from any other device does not exist yet, and neither does handling input in a user-space driver. - **Capability transfer**: a key cannot be handed to another task inside a message (capability transfer over IPC). - **Hardware interrupt notification**: a program cannot be told about hardware interrupts (Notification objects). -- **Crash reports**: a crashed task is only stopped. It is not reported to a handler task. +- **Crash reports**: a crashed task is only stopped. It is not reported to a handler task. A program that holds the key to the task can ask whether it has ended (TCB_STATUS), and it learns neither when nor why. - **Multicore**: only one processor core is used. - **Device access**: programs cannot access hardware devices (device memory and interrupts). - **Loading new executable code after boot**: this is the flip side of the write-or-run rule. Executable memory exists only for the root task image, so a confined task runs code from that image. - **A use for the time partitions**: the mechanism exists and is tested at every boot, but no image puts its tasks into more than one domain yet. Putting the signing oracle's vault into a domain of its own is future work. - **Multi-level key lookup and ASIDs**: multi-level key lookup and hardware address space tags (ASIDs) do not exist. Today every switch to another address space empties the processor's cache of memory map lookups (the TLB). - **More for the signing oracle**: the oracle has the following limits today. - - No persistence: the key lives only in memory and is gone after a reboot or ZEROIZE. + - No persistence: the key lives only in memory and is gone after a reboot, after ZEROIZE or when the vault task ends. - One key only, and no way to import or export a key. - No post-quantum (PQC) algorithm yet. - No authentication of the operator: the terminal reads the serial line, and whoever holds the line is the operator. In service mode no signing client uses the key yet. @@ -354,13 +356,14 @@ In the following table, you can find the contents of each path in the repository | `crates/k0-part` | Every scheduling decision: which domain runs at which tick under the time partition table, and which task of it runs. Also the arithmetic of tick instants. It touches no hardware and is tested on the host | | `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-cap` | Keys and their rights, key rings, the derivation list, untyped memory, retype, split, 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` | The kernel side of the scheduler: one ready queue and one list of timed waiters per domain, and the installed task. The decisions are made by `k0-part` | | `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`) | +| `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 and the supervision of the terminal and the vault (`service.rs`) | +| `userspace/k0-sup` | The rules by which the root task supervises the terminal and the vault: when a service that ended is taken back, when it is started again and how often. It makes no system call, has no `unsafe` code and is tested on the host | | `userspace/k0-term` | The operator terminal: line editing, command parsing and the requests to the vault | | `userspace/k0-vault` | The signing oracle service: protocol and fixed policy, the request handling, and the boundary around the crypto crate | | `tools/` | QEMU runner (also for `.efi` files), boot test, boot matrix, terminal session test (`term-test.py`), boot log reader, host test, loader build (`build-loader.sh`), PE and instruction order check (`pe-check.py`), device tree editor for hostile boot input (`fdt-patch.py`) | diff --git a/INTRODUCTION_KR.md b/INTRODUCTION_KR.md index 285bf37..08dae7a 100644 --- a/INTRODUCTION_KR.md +++ b/INTRODUCTION_KR.md @@ -132,14 +132,15 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - 주소 공간(AddrSpace) 메모리는 그 주소 공간의 열쇠를 보여 줘야만 그 주소 공간의 지도에 올릴 수 있습니다(MAP, UNMAP). 열쇠에는 권한(읽기, 쓰기, 실행)이 있습니다. 우편함 열쇠에는 누가 보냈는지 받는 쪽에 알려 주는 표식(배지)을 붙일 수 있습니다. 열쇠는 권한을 그대로 두거나 줄여서 복사하거나, 다른 슬롯으로 옮길 수 있습니다(CAP_COPY, CAP_MOVE). -- **태스크 실행**: 태스크는 준비할 때 열쇠고리 하나와 주소 공간 하나에 묶이고(TCB_CONFIGURE) 그다음 시작됩니다(TCB_RESUME). 태스크는 차례를 돌아가며 실행되고, 너무 오래 도는 태스크는 타이머가 끊습니다(타이머 선점이 있는 라운드 로빈 스케줄링). 두 타이머 틱 사이에 실행을 넘겨받은 태스크는 한 주기를 온전히 받습니다. 처음 만나는 틱은 그 태스크를 끊지 않으므로, 타이머가 CPU를 빼앗기 전에 최소 한 주기, 많아야 두 주기을 실행합니다. 이렇게 해서 태스크가 틱 직전에 `YIELD`를 호출해 다음 태스크의 차례를 줄이는 일을 막습니다. 태스크는 자기 차례를 양보하거나(YIELD) 끝낼 수 있습니다(EXIT). +- **메모리 예산**: 빈 메모리 블록에서 더 작은 블록을 잘라낼 수 있습니다(UNTYPED_SPLIT). 크기는 그래뉼 단위로 주고, 오브젝트 하나는 그래뉼 하나를 차지합니다. 그래서 작은 블록만 받은 태스크는 오브젝트를 정확히 그만큼만 만들 수 있습니다. 큰 블록을 회수하면 작은 블록과 거기서 만든 것이 전부 사라집니다. 이것은 태스크가 가진 메모리의 양을 제한합니다. 커널이 그 태스크를 위해 일하는 시간은 제한하지 않습니다("격리가 어디까지 지켜 주는가" 참고). +- **태스크 실행**: 태스크는 준비할 때 열쇠고리 하나와 주소 공간 하나에 묶이고(TCB_CONFIGURE) 그다음 시작됩니다(TCB_RESUME). 태스크는 차례를 돌아가며 실행되고, 너무 오래 도는 태스크는 타이머가 끊습니다(타이머 선점이 있는 라운드 로빈 스케줄링). 두 타이머 틱 사이에 실행을 넘겨받은 태스크는 한 주기를 온전히 받습니다. 처음 만나는 틱은 그 태스크를 끊지 않으므로, 타이머가 CPU를 빼앗기 전에 최소 한 주기, 많아야 두 주기을 실행합니다. 이렇게 해서 태스크가 틱 직전에 `YIELD`를 호출해 다음 태스크의 차례를 줄이는 일을 막습니다. 태스크는 자기 차례를 양보하거나(YIELD) 끝낼 수 있습니다(EXIT). 태스크의 열쇠를 가진 프로그램은 그 태스크가 시작 전인지, 살아 있는지, 끝났는지 커널에 물을 수 있습니다(TCB_STATUS). 커널은 끝난 이유를 알려 주지 않고, 스스로 누구에게 알리지도 않습니다. - **시간 분할**: 모든 태스크는 도메인이라고 부르는 8개 묶음 가운데 하나에 속합니다. 항목이 최대 16개인 시간표(시간 분할 표)가 어느 도메인이 어느 초에 프로세서를 사용할 수 있는지 정하고, 이 표는 되풀이됩니다. 도메인은 그 표에 있는 자기 창에서만 실행됩니다. 도메인이 자기 창에서 실행할 것이 없으면 프로세서는 기다리며, 그 시간은 다른 도메인에 넘어가지 않습니다. 도메인이 바뀌는 틱 앞에서는 커널이 타이머 인터럽트를 25 ms 일찍 받아 전환을 하고, 그런 다음 그 틱의 시각이 될 때까지 기다립니다. 그때 하고 있던 커널 작업과 전환이 그 25 ms 안에 들어가는 한, 다음 도메인은 기다리는 루프와 커널에서 나가는 길만큼의 오차 안에서 그 시각에 시작합니다. - **누가 정하나**: 루트 태스크가 부팅 때 받는 열쇠 하나(제어 케이퍼빌리티 `PartCtl`)가 있어야 표를 정하고(PART_SET_TABLE), 아직 실행된 적 없는 태스크를 도메인에 넣을 수 있습니다(PART_SET_DOMAIN). 이 열쇠는 복사할 수 없고, 지우면 표와 도메인이 다음 부팅까지 고정됩니다. - **표가 없을 때**: 도메인은 하나이고, 태스크는 위에 적은 대로 차례를 돌아가며 실행됩니다. - **아직 어떤 이미지도 사용하지 않습니다**: 루트 태스크가 부팅할 때마다 자가 테스트에서 이 메커니즘을 시험해 본 뒤 열쇠를 지웁니다. 그래서 지금 빌드하는 모든 이미지는 도메인 하나로 실행됩니다. 시간 분할이 무엇을 막고 무엇을 막지 못하는지는 [SECURITY_KR.md](SECURITY_KR.md)와 [design/kr/scheduling_KR.md](design/kr/scheduling_KR.md#시간-분할)에 있습니다. - **메시지**: 태스크는 프로세서 레지스터에 담긴 짧은 메시지를 주고받습니다. 보내는 쪽은 받는 쪽이 메시지를 가져갈 때까지 기다립니다(동기 IPC: SEND, RECV, CALL, REPLY_RECV). 보내려면 우편함 열쇠에 쓰기 권한이, 받으려면 읽기 권한이 있어야 합니다. 받는 쪽은 보낸 쪽 열쇠의 표식을 알게 되고, 답장할 권리는 한 번만 사용할 수 있습니다. - **타임아웃**: 이 호출들은 모두 제한 시간을 줄 수 있습니다. 단위는 타이머 틱입니다(1틱은 1초). 제한 시간 안에 상대가 오지 않으면 호출이 오류(`TIMEOUT`, 또는 `CALL`이 전달됐지만 답이 오지 않은 경우 `REPLY_TIMEOUT`)로 돌아옵니다. 제한 시간을 주지 않으면 태스크는 필요한 만큼 계속 기다립니다. 기다리는 시간은 준 틱 수 이상이며 조금 더 길 수 있습니다. 제한 시간은 태스크가 다시 준비 상태가 되는 때를 정할 뿐, 실행되는 때를 정하지는 않습니다. -- **대기 상태**: 실행할 수 있는 태스크가 없어도 커널은 더 이상 멈추지 않습니다. 다음 인터럽트를 기다리다가, 제한 시간이 지난 태스크를 깨우고 계속 진행합니다. 태스크를 깨울 수 있는 것이 아무것도 없으면 기계는 대기 상태로 남고, 부트 로그에 `k0: all tasks stopped (none ready, no timeout pending)`이 찍힙니다. 시간 제한이 걸린 대기도, 콘솔 입력을 기다리는 태스크도 없을 때만 이 줄이 찍힙니다. 터미널 이미지는 입력을 기다리는 것이 정상이라 아무것도 출력하지 않습니다. +- **대기 상태**: 실행할 수 있는 태스크가 없어도 커널은 더 이상 멈추지 않습니다. 다음 인터럽트를 기다리다가, 제한 시간이 지난 태스크를 깨우고 계속 진행합니다. 태스크를 깨울 수 있는 것이 아무것도 없으면 기계는 대기 상태로 남고, 부트 로그에 `k0: all tasks stopped (none ready, no timeout pending)`이 찍힙니다. 시간 제한이 걸린 대기도, 콘솔 입력을 기다리는 태스크도 없을 때만 이 줄이 찍힙니다. 서비스 중인 터미널 이미지는 이때 아무것도 출력하지 않습니다. 터미널은 입력을 기다리고, 루트 태스크는 서비스를 한 번 살펴본 뒤 다음에 살펴볼 때까지 제한 시간을 걸고 기다리기 때문입니다. - **부팅 때 크기를 정하는 커널 표**: 커널은 자신이 쓸 페이지 테이블과 주소 공간 항목의 메모리를 부팅할 때 따로 떼어 둡니다. 크기는 커널이 내어 주는 메모리에 비례합니다(RAM의 약 0.4 %). 그래서 태스크가 이 표들을 다 사용해 버릴 수 없고, 주소 공간의 수는 메모리로만 제한됩니다. - **충돌 격리**: 태스크가 죽거나, 커널이 모르는 시스템 콜을 부르거나, 끝나면 그 태스크만 멈춥니다(폴트 격리). - **태스크 격리와 열쇠 회수**: 서로 다른 열쇠고리와 주소 공간에 묶인 태스크는 서로의 메모리와 열쇠에 닿을 수 없습니다. 모든 열쇠는 어느 열쇠에서 복사됐는지 기억합니다(파생 목록). 열쇠를 회수하거나(CAP_REVOKE) 지우면(CAP_DELETE) 다음 일이 일어납니다. @@ -168,13 +169,14 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. ``` `cargo run` 아래에서는 QEMU 자신의 탈출 키가 Ctrl-A라서(Ctrl-A 다음 X로 QEMU 종료) Ctrl-A는 K0에 닿지 않습니다. - - **시작 순서**: 터미널 이미지는 자가 테스트를 모두 실행한 다음, 루트 태스크가 새 볼트를 시작해 부팅 시드를 건네고(`root: vault seeded`), 터미널과 똑같이 연결한 적대 태스크 둘이 거부되고 폴트로 끝나는지 확인한 뒤(`root: terminal wiring holds`), 자기 관리자 열쇠를 버리고 터미널을 시작합니다(`root: service started`). 그 뒤 배너 `K0 operator console, type 'help'`와 프롬프트 `k0> `가 나옵니다. 입력 경로가 없는 기계에서는 `root: no console input, terminal not started`가 나오고 터미널은 시작하지 않습니다. + - **시작 순서**: 터미널 이미지는 자가 테스트를 모두 실행한 다음, 루트 태스크가 볼트를 다시 시작하는 방법을 시험해 보고(`root: vault restart test pass`), 새 볼트를 시작해 부팅 시드를 건네고(`root: vault seeded`), 터미널과 똑같이 연결한 적대 태스크 둘이 거부되고 폴트로 끝나는지 확인한 뒤(`root: terminal wiring holds`, `root: terminal restart test pass`), 자기 관리자 열쇠를 버리고 터미널을 시작합니다(`root: service started`). 그 뒤 배너 `K0 operator console, type 'help'`와 프롬프트 `k0> `가 나옵니다. 입력 경로가 없는 기계에서는 `root: no console input, terminal not started`가 나오고 터미널은 시작하지 않습니다. + - **감독**: 시작한 뒤에도 루트 태스크는 터미널과 볼트를 계속 지켜봅니다. 두 번째 틱마다 두 태스크가 아직 살아 있는지 커널에 묻습니다. 하나가 끝났으면 루트 태스크는 그 태스크를 만든 메모리 블록을 되찾고 같은 자리에 태스크를 다시 만듭니다. 서비스마다 부팅당 최대 3번이고, 적어도 2, 8, 32틱을 기다린 뒤입니다. 끝난 볼트의 메모리는 먼저 지우며, 그 자리에 시작하는 볼트에는 키가 없습니다. 부팅 시드는 한 번 쓰였기 때문입니다. 그래서 볼트를 다시 시작한 뒤에는 다음 부팅까지 키가 없습니다. 그때 루트 태스크가 출력하는 줄(예: `root: vault started again without a key`)은 [USAGE_KR.md](USAGE_KR.md)에 있습니다. - **명령**: `help`, `vault status`(볼트 상태), `vault pubkey`(공개 키), `vault keygen ed25519`(키 만들기), `vault zeroize confirm`(키 지우기)이 있습니다. `vault zeroize`만 입력하면 지우지 않고 `err confirm-required`가 나옵니다. 모든 명령은 `ok` 또는 `err <이유>` 한 줄로 끝납니다. `vault status`는 항상 `validated=no`를 출력합니다. 구현이 어떤 검증도 받지 않았기 때문입니다. 자세한 사용법과 예시 화면은 [USAGE_KR.md](USAGE_KR.md)에 있습니다. - **입력 규칙**: 줄은 Enter(CR 또는 LF)로 끝나고 64자까지이며 출력할 수 있는 ASCII만 받습니다. Backspace와 DEL은 한 글자를 지우고, Ctrl-C와 Ctrl-U는 줄을 취소하며, 방향키 같은 ESC 열은 무시합니다. 프롬프트가 나오기 전에 UART에 도착한 바이트는 버립니다. 입력이 유실되면 다음 줄 끝까지 모두 버리고 `err input-lost`를 출력합니다. - **커널이 하는 일**: 커널은 UART에서 받은 바이트를 256바이트 링에 쌓기만 하고 해석하지 않습니다. 태스크는 시스템 콜 `CONSOLE_READ`로 한 번에 한 바이트씩 가져가며, 한 번에 한 태스크만 기다릴 수 있습니다. 수신 인터럽트는 어떤 태스크가 처음 입력을 읽을 때까지 꺼져 있습니다. 그때 `k0: tick lines off (console input in use)` 한 줄을 남기고 주기적인 `k0: tick N` 줄이 멈추지만 타이머, 선점, 제한 시간은 계속 동작합니다. 링이 차면 커널이 수신 인터럽트를 스스로 막았다가 태스크가 절반을 가져간 뒤 다시 열어서, 입력이 몰려도 커널의 일은 읽는 쪽 속도로 제한됩니다. 부팅 때 `k0: console input on (pl011 irq 33)` 또는 `k0: console input off (<이유>)`가 출력됩니다. 틀린 인터럽트 번호는 입력만 끄고 부팅은 막지 않습니다. - **인증이 없습니다**: 시리얼 줄을 쥔 사람이 곧 운영자이고, 운영자의 네 가지 일(상태, 공개 키, 키 만들기, 키 지우기)을 모두 할 수 있습니다. 키를 지워 서비스를 멈추게 하는 것까지 포함하며, 이것은 설계에 따른 것입니다. 서명을 받거나 정책을 바꾸지는 못합니다. - **화면을 믿으면 안 됩니다**: 커널 줄이 입력 도중에 끼어들면 화면의 줄은 갈라져 보이지만 입력 버퍼는 온전하고, Enter를 치면 버퍼 전체가 실행됩니다. 콘솔 출력을 가진 태스크는 커널이나 루트 태스크 줄처럼 보이는 줄을 아무거나 출력할 수 있어서 줄 머리말은 아무것도 증명하지 않습니다. 터미널은 거기에 더해 자기 줄 안에서 글자를 지울 수 있습니다(백스페이스 출력). - - **알려진 한계**: 터미널과 볼트는 죽어도 다시 시작하지 않습니다(루트 태스크는 신뢰합니다). 서비스 모드에는 서명을 요청하는 클라이언트가 아직 없어서 키는 만들고 보여 줄 뿐 다른 태스크가 쓰지 못합니다(클라이언트의 서명은 자가 테스트가 보여 줍니다). 터미널 출력은 부트 로그의 사용자 몫을 차지하므로, 그 몫이 차면 이후 태스크 출력은 기록되지 않습니다. + - **알려진 한계**: 터미널과 볼트를 지켜보는 루트 태스크는 신뢰 대상이며, 루트 태스크를 지켜보는 것은 없습니다. 루트 태스크는 끝난 태스크만, 최대 두 틱 늦게 알아채고, 멈춰 있는 태스크는 알아채지 못합니다. 서비스 중에 실제 터미널이나 실제 볼트를 끝내는 테스트는 없습니다. 대기와 3번이라는 한도는 빌드하는 컴퓨터에서만 테스트하고, 부팅할 때마다 서비스별로 재시작 한 번을 대기 없이 시험합니다. 서비스 모드에는 서명을 요청하는 클라이언트가 아직 없어서 키는 만들고 보여 줄 뿐 다른 태스크가 쓰지 못합니다(클라이언트의 서명은 자가 테스트가 보여 줍니다). 터미널 출력은 부트 로그의 사용자 몫을 차지하므로, 그 몫이 차면 이후 태스크 출력은 기록되지 않습니다. 위 항목은 전부 루트 태스크가 부팅할 때마다 자가 테스트로 확인합니다. 서명 오라클과 터미널은 그것을 포함해 빌드한 이미지에서 테스트합니다. @@ -279,7 +281,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - 타임아웃 없이 기다리는 태스크는 상대가 끝내 행동하지 않으면 영원히 기다릴 수 있습니다. 타임아웃은 호출마다 주는 것이라서, 계속 응답해야 하는 서버는 모든 대기에 타임아웃을 줘야 합니다. - 우선순위와 CPU 예산이 없습니다. 태스크는 돌아가며 실행되고, 빈 메모리를 많이 가진 태스크는 태스크를 많이 만들어 다른 태스크의 몫을 줄일 수 있습니다. 양보하거나 기다리지 않는 태스크는 준비된 태스크가 N개일 때 오래 보면 CPU의 1/N 이상을 가집니다. 이는 최대 6개 태스크까지 모델에서 탐색으로 확인하고 호스트 테스트로 검사한 것입니다. 기계가 검사한 증명은 도메인 하나의 모델에 대해서만 있고, 코드에 대해서도 도메인이 여럿인 경우에 대해서도 없습니다. 태스크를 만들 때마다 N이 커집니다. - 스케줄러를 통한 타이밍 채널이 한 도메인의 태스크 사이에서 열려 있습니다. 태스크는 양보하거나 기다릴 시점을 골라 자기 도메인의 다른 태스크가 언제, 얼마나 오래 실행되는지를 여전히 바꿀 수 있습니다. 이는 분석하지 않았습니다. 도메인 사이에서는 시간 분할이 이를 막는 메커니즘입니다. 하지만 태스크를 둘 이상의 도메인에 넣는 이미지는 아직 없고, 이 메커니즘에는 그 자체의 한계가 있습니다([SECURITY_KR.md](SECURITY_KR.md) 참고). K0는 실시간 또는 지연 시간에 대한 약속을 하지 않습니다. 틱은 1초이고 커널은 중단할 수 없습니다. 한 번에 한 주기에서 두 주기라는 값은 이 버전의 동작이며 인터페이스가 아닙니다. - - 커널은 시스템 콜을 처리하는 동안 중단할 수 없습니다. 큰 메모리 블록의 열쇠를 회수하는 것 같은 긴 호출은 다른 모든 태스크와 모든 타임아웃을 늦춥니다. + - 커널은 시스템 콜을 처리하는 동안 중단할 수 없습니다. 큰 메모리 블록의 열쇠를 회수하는 것 같은 긴 호출은 다른 모든 태스크와 모든 타임아웃을 늦춥니다. 태스크에 더 작은 블록만 주면(UNTYPED_SPLIT) 그 태스크가 가진 메모리의 양과 오브젝트의 수가 제한됩니다. 그런 호출이 걸리는 시간은 제한되지 않습니다. 시간은 복사본을 포함해 제거되는 열쇠의 수를 따르기 때문입니다. - 커널 안의 치명적 오류, 또는 커널이 한 태스크의 탓으로 돌릴 수 없는 하드웨어 오류는 여전히 기계 전체를 멈춥니다. - 태스크가 끝날 때 커널이 내는 줄(충돌, 종료, 알 수 없는 시스템 콜)은 부트 로그의 4 KiB를 나눠 쓰며, 더는 커널 부분을 채우지 못합니다. 태스크를 만들 수 있는 태스크는 여전히 다른 태스크의 그런 줄을 로그에서 밀어낼 수 있습니다. - 서명 오라클도 예외가 아닙니다. 클라이언트는 볼트로 가는 우편함 하나를 함께 사용하므로 모든 호출에 타임아웃을 줘야 하며, 그렇지 않으면 멈춘 볼트가 클라이언트를 붙잡습니다. @@ -300,14 +302,14 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - **입력의 나머지**: 콘솔 UART의 입력만 있습니다(PL011과 SBSA UART, 선택 사항). 16550 콘솔과 다른 장치의 입력은 아직 없습니다. 입력을 사용자 공간 드라이버로 처리하는 것도 아직 없습니다. - **케이퍼빌리티 전송**: 메시지에 열쇠를 담아 다른 태스크에 넘기는 기능입니다(IPC를 통한 케이퍼빌리티 전송). - **하드웨어 인터럽트 알림**: 하드웨어 인터럽트를 프로그램에 알려 주는 기능입니다(Notification 오브젝트). -- **죽은 태스크 통지**: 죽은 태스크를 멈추기만 하지 않고 처리 담당 태스크에 알려 주는 기능입니다. +- **죽은 태스크 통지**: 죽은 태스크를 멈추기만 하지 않고 처리 담당 태스크에 알려 주는 기능입니다. 태스크의 열쇠를 가진 프로그램은 그 태스크가 끝났는지 물을 수 있지만(TCB_STATUS), 언제 왜 끝났는지는 알 수 없습니다. - **멀티코어**: 여러 프로세서 코어입니다. 지금은 코어 하나만 사용합니다. - **장치 접근**: 프로그램이 하드웨어 장치를 쓰게 해 주는 기능입니다(장치 메모리와 인터럽트). - **부팅 뒤 새 실행 코드 적재**: 쓰기와 실행을 함께 허용하지 않는 규칙의 대가입니다. 실행 가능한 메모리는 루트 태스크 이미지에만 있어서 격리된 태스크도 그 이미지의 코드를 실행합니다. - **시간 분할의 쓰임새**: 메커니즘은 있고 부팅할 때마다 테스트하지만, 태스크를 둘 이상의 도메인에 넣는 이미지는 아직 없습니다. 서명 오라클의 볼트를 자기만의 도메인에 두는 것은 앞으로 할 일입니다. - **여러 단계의 열쇠 조회와 ASID**: 여러 단계의 열쇠 조회, 하드웨어 주소 공간 표식(ASID)입니다. 지금은 다른 주소 공간으로 바꿀 때마다 프로세서가 메모리 지도 조회 결과를 담아 두는 캐시(TLB)를 전부 비웁니다. - **서명 오라클의 남은 한계**: 오라클에는 지금 다음 한계가 있습니다. - - 영속성이 없습니다. 키는 메모리에만 있고 재부팅이나 ZEROIZE 뒤에는 사라집니다. + - 영속성이 없습니다. 키는 메모리에만 있고 재부팅이나 ZEROIZE 뒤에, 또는 볼트 태스크가 끝나면 사라집니다. - 키는 하나뿐이며, 키를 가져오거나 내보내는 방법이 없습니다. - 양자내성(PQC) 알고리즘은 아직 없습니다. - 운영자의 인증이 없습니다. 시리얼 줄에서 입력하는 터미널은 있지만 줄을 쥔 사람이 곧 운영자입니다. 서비스 모드에서 키를 쓰는 서명 클라이언트도 아직 없습니다. @@ -355,13 +357,14 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. | `crates/k0-part` | 모든 스케줄링 판정. 시간 분할 표에 따라 어느 틱에 어느 도메인이 실행되는지, 그 도메인의 어느 태스크가 실행되는지를 정합니다. 틱 시각의 산술도 여기에 있습니다. 하드웨어를 건드리지 않으며 호스트에서 테스트합니다 | | `crates/k0-boot` | 디바이스 트리 파서, 내장된 루트 태스크 이미지와 무결성 검사, PAC 키 파생, 부트 메모리 창 탐색(로더와 공유) | | `crates/k0-efi` | `unsafe` 없는 로더의 논리. UEFI 메모리 맵에서 RAM 계획, 펌웨어 디바이스 트리 고쳐 쓰기, 결과의 독립적인 재검사, 커널 이미지 헤더 검사. 점프 전에 결과에 커널 자신의 디바이스 트리 코드를 돌려 봅니다 | -| `crates/k0-cap` | 열쇠와 권한, 열쇠고리, 파생 목록, untyped 메모리, retype, revoke와 delete | +| `crates/k0-cap` | 열쇠와 권한, 열쇠고리, 파생 목록, untyped 메모리, retype, 분할, revoke와 delete | | `crates/k0-mm` | 커널 페이지 테이블, 메모리 지도 켜기(MMU), 프로그램 주소 공간과 그 등록부 | | `crates/k0-task` | 열쇠고리와 주소 공간에 묶인 태스크, 우편함, 루트 태스크 적재 | | `crates/k0-sched` | 스케줄러의 커널 쪽. 도메인마다 준비 큐 하나와 기한이 있는 대기자 목록 하나를 두고, 설치된 태스크를 유지합니다. 판정은 `k0-part`가 내립니다 | | `crates/k0-ipc` | 동기 메시지 | | `loader/` | 빌드된 커널 이미지를 품고 시작시키는 UEFI 응용 프로그램(`k0-loader`, 타겟 `aarch64-unknown-uefi`). UEFI 호출, 흐름, 마지막의 캐시 비우기·MMU 끄기·점프 | -| `userspace/root-task` | 첫 프로그램과 자가 테스트, 서명 오라클의 연결과 자가 테스트(`oracle.rs`), 터미널 서비스의 시작(`service.rs`) | +| `userspace/root-task` | 첫 프로그램과 자가 테스트, 서명 오라클의 연결과 자가 테스트(`oracle.rs`), 터미널과 볼트의 시작과 감독(`service.rs`) | +| `userspace/k0-sup` | 루트 태스크가 터미널과 볼트를 감독하는 규칙. 끝난 서비스를 언제 되찾고, 언제 다시 시작하고, 몇 번까지 하는지를 정합니다. 시스템 콜을 하지 않고, `unsafe` 코드가 없으며, 호스트에서 테스트합니다 | | `userspace/k0-term` | 운영자 터미널. 줄 편집, 명령 해석, 볼트로 보내는 요청 | | `userspace/k0-vault` | 서명 오라클 서비스. 프로토콜과 고정 정책, 요청 처리, 암호 크레이트를 감싸는 경계 | | `tools/` | QEMU 러너(`.efi`도 지원), 부팅 테스트, 부팅 매트릭스, 터미널 대화 테스트(`term-test.py`), 부트 로그 읽기, 호스트 테스트, 로더 빌드(`build-loader.sh`), PE와 명령 순서 검사(`pe-check.py`), 적대적인 부팅 입력을 만드는 디바이스 트리 편집(`fdt-patch.py`) | diff --git a/SECURITY.md b/SECURITY.md index 3d346a4..d5c2a55 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -56,8 +56,10 @@ A confined task has the following properties: - **Bindings**: both bindings are held as capabilities inside the task's TCB. If either capability is revoked or deleted, the task is torn down. - **Scope of isolation**: isolation holds between tasks bound to different CNodes and address spaces. Tasks that share them, as the root task's helper threads do, are threads of one another. Whoever holds a task's TCB, CNode or AddrSpace capability controls that task. - **Rights**: capabilities carry rights (R, W, X). Rights can only be removed by `CAP_COPY`, never added. `Endpoint` capabilities can carry a badge, set once by `CAP_COPY`, which the receiver sees. The `Console` capability carries R (read input) and W (write output) in the same way. Retyped frames never gain X, and X exists only on the root task's text frames, so no physical frame is writable in one place and executable in another. -- **Derivation and teardown**: capabilities form a derivation list. `CAP_REVOKE` removes everything derived from a capability, `CAP_DELETE` also removes the slot, an object is finalized when its original capability is removed, and the underlying `Untyped` memory can then be retyped again. Retyped objects are zeroed before a capability to them exists. +- **Derivation and teardown**: capabilities form a derivation list. `CAP_REVOKE` removes everything derived from a capability, `CAP_DELETE` also removes the slot, an object is finalized when its original capability is removed, and the underlying `Untyped` memory can then be retyped again. Retyped objects are zeroed before a capability to them exists. `CAP_REVOKE` and `CAP_DELETE` themselves do not zero the memory they free: a granule is zeroed when `RETYPE` makes an object of it again. +- **Memory budgets**: `UNTYPED_SPLIT` (system call 19) cuts a smaller `Untyped` capability, a child of a given number of granules, out of an `Untyped` capability. Every object is one granule, so a task that holds only a child of n granules gets exactly n objects from it and no more. A child cannot be copied, it can be moved into the CNode of another task, and it can be split again. Revoking the parent removes the child and everything made from it. Revoking the child gives the memory back to the child, not to the parent. [design/en/capabilities.md](design/en/capabilities.md#untyped-split) has the rules. What a child does not bound is listed under "Availability" below. - **Fault isolation**: a fault, an exit, or an unknown system call in a confined task terminates only that task. +- **Task status**: `TCB_STATUS` (system call 20) tells the holder of a `Tcb` capability whether the task has not started, is alive or has ended. It changes nothing and gives no reason for the end. `Tcb` capabilities carry no rights, so every holder may ask. The kernel tells nobody by itself. What is still NOT provided on `main`: @@ -69,11 +71,11 @@ What is still NOT provided on `main`: - 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. - The kernel no longer chooses the entry kind of a task. It names the event, and one piece of code that is tested on the host (`crates/k0-part`) chooses. The three mistakes that no test on the real kernel would have seen (the tick's own switch, the wait loop's report of a tick, the entry kind at the hand-off to the root task) are therefore covered by host tests of that code. What no test sees now is listed under "Fixed time partitions": the guard, the hold before the return to EL0, the TLB flush at a change of domain and the console rule under a table. The queues and timed lists around that code (`crates/k0-sched`, `crates/k0-ipc`) have no host tests and are covered by the boot test and by review. - 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. An `Untyped` capability cannot be split or capped, so a task that is given one can do this with all of it. Hand `Untyped` only to a task that is trusted with the availability of the whole system. The root task gives none to the terminal or the vault. + - 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. An `Untyped` capability can be split, and a child `Untyped` bounds two things for a task that holds no other `Untyped`: how much memory the task can use, and so how many objects it can have at one time. It does not bound time. `CAP_REVOKE` and `CAP_DELETE` still take time in proportion to the number of capabilities they remove, copies included, with interrupts masked, and a revoke that can be interrupted and continued does not exist. A task that is given any `Untyped`, a child included, can therefore still delay everybody. Hand `Untyped` only to a task that is trusted with the availability of the whole system. The root task gives none to the terminal or the vault: the slabs those two are built from stay in the root task's CNode. - A `k0_arch::fatal` or a kernel panic still stops the machine, and so does an SError taken from EL0. - Filling the kernel part of the boot log with fault and exit lines is addressed on `main`. The lines the kernel prints when a task ends (a fault, an exit, an unknown system call) now have their own share of the log, 4 KiB, and stop before the last 2 KiB, which stay for the kernel. The kernel says so once (`k0: task lines over the log quota, later ones go to the console only`). Past that share such a line goes to the console only, so an image without a console driver loses it. What this protects is the kernel's own lines and that last part. All tasks share the one share, so a task that can create tasks can still push the fault and exit lines of other tasks out of the log. A boot with the terminal and the vault uses about a quarter of the share. - **Kernel resource exhaustion**: at boot the kernel reserves the page tables and the address space registry entries that the memory it hands out as `Untyped` can need, taking them from the top of each range. `RETYPE` therefore no longer fails with `KERNEL_RESOURCE` for lack of page tables, and the number of address spaces is limited only by memory. The reserve costs about 0.4 % of RAM with the 4 KiB granule (about 0.2 % each for the page tables and for the registry entries). A range that is too small for its own reserve is not handed out as `Untyped`, and neither is a range without one whole page. -- **Missing features**: no fault delivery to a handler task, no notifications, and no capability transfer over IPC. +- **Missing features**: no fault delivery to a handler task, no notifications, and no capability transfer over IPC. A task learns that another task ended only by asking with `TCB_STATUS`, which needs the `Tcb` capability and gives no reason. - **Time visible to EL0**: EL0 still cannot read any hardware counter or timer. IPC timeouts give a task a clock as coarse as the scheduler tick (1 second) and a wake-up aligned to the timer interrupt. Whether that can be amplified into a usable timing source for cache or speculation attacks has not been analysed. - **Sender after revoke**: a sender already queued on an endpoint still delivers once after its capability is revoked. - **Serial line**: in an image built with the features `console-input` or `terminal`, an outside party can reach the kernel through the serial line. The operator terminal has no authentication, an outside party can cause interrupts while tasks run, and input waits behind running tasks. See "Serial input and the operator terminal". @@ -85,7 +87,7 @@ What is still NOT provided on `main`: - **Source of output**: kernel output and task output share one boot log, and in an image built with a console driver also one console. A line does not say who wrote it. A task that holds a `Console` capability with the write right can print a line that starts with `k0:`. The kernel replaces control bytes and limits how much of the boot log task output may use, but nothing that reads the console or the log, including `tools/qemu-boot-test.sh`, can treat a `k0:` line printed after `k0: entering root task (el0)` as written by the kernel. This includes the `k0: console drivers [...]` line (see "Optional console output"). - **Trap to EL2**: isolation covers confidentiality and integrity, not availability. A trap to EL2 after the kernel has stepped down to EL1 parks the whole machine by design. - **Entry at EL2**: entry at EL2 relies on the firmware contract that Linux also uses: an EL3 firmware must enable the fine-grained-trap and HCRX controls when those features exist. -- **Root task**: the root task is still trusted and holds the initial `Untyped` capabilities, and `write_bootinfo` still exposes their physical addresses to it. It also holds the control capability of the time partitions until it deletes it at the end of its self-tests. In an image with the signing oracle it also builds the vault and could read the vault's memory (see "The signing oracle"). In an image with the feature `terminal` it also starts the terminal task and is not restarted if the terminal or the vault dies. +- **Root task**: the root task is still trusted and holds the initial `Untyped` capabilities, and `write_bootinfo` still exposes their physical addresses to it. It also holds the control capability of the time partitions until it deletes it at the end of its self-tests. In an image with the signing oracle it also builds the vault and could read the vault's memory (see "The signing oracle"). In an image with the feature `terminal` it also starts the terminal task and supervises the terminal and the vault (see "Serial input and the operator terminal"). Nothing supervises the root task itself. > [!WARNING] > Even on `main`, treat running untrusted code as experimental. The availability limits above still apply. @@ -241,7 +243,9 @@ What the kernel does with input: What the terminal is: - **Isolation**: the terminal is a task in its own address space with two capabilities: a `Console` copy with R and W, and the vault endpoint with the send right and the operator badge. The vault's response frame is mapped read-only for it. -- **Start**: after the self-tests, the root task starts a new vault, hands it the boot seed, runs two hostile tasks wired exactly like the terminal (they must be refused and end in a fault), drops its admin capability, starts the terminal and blocks for ever. The lines `root: terminal wiring holds` and `root: service started` report this. On a machine without an input path the root task prints `root: no console input, terminal not started`. +- **Start**: after the self-tests, the root task of an image with a vault tries the restart path of the vault on a vault that never gets a seed, starts a new vault and hands it the boot seed. In every terminal image it then runs two hostile tasks wired exactly like the terminal (they must be refused and end in a fault), drops its admin capability and starts the terminal. The lines `root: vault restart test pass`, `root: terminal wiring holds`, `root: terminal restart test pass` and `root: service started` report this. On a machine without an input path the root task prints `root: no console input, terminal not started`. +- **Supervision**: after `root: service started` the root task does not block for ever. At every second tick it asks the kernel with `TCB_STATUS` whether the terminal task and the vault task ended. It waits only on an endpoint that it alone holds, so a service cannot hold it up. Each service is built from its own slab, a child `Untyped` of 16 granules that stays in the root task's CNode. When a service ended, the root task revokes the slab, which removes everything the service was made of, and builds the service again in the same slab and the same slots. A service is started again at most 3 times per boot, after waits of at least 2, 8 and 32 ticks, and the budget is not refilled. The terminal is not started again on a machine without a console input path. When the terminal is down for good, a vault that is still up is stopped and erased. The policy is the crate `userspace/k0-sup`, which has no `unsafe` code and no dependencies and is tested on the host. [design/en/terminal.md](design/en/terminal.md#supervision) has the details and the log lines. +- **Erasing an ended vault**: before the slab of an ended vault is used for anything else, the root task retypes all 16 granules of it as frames, which zeroes each one, and requires that a 17th `RETYPE` returns `EXHAUSTED`. It also zeroes the operator response frame. **A vault that is started again has no seed and no key and refuses INIT**, because the boot seed was used once and is gone. After a vault restart there is no key until the machine is booted again. - **Input rules**: a line is at most 64 printable ASCII characters. The terminal drops what reached the UART before the prompt, and a reported loss discards everything up to the next line end (`err input-lost`). The limits are as follows: @@ -256,7 +260,7 @@ The limits are as follows: 8. If a kernel line appears while the operator is typing, the screen line is split but the buffer is whole, and Enter runs the whole buffer. 9. 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. 10. No signing client exists in service mode. The vault's key is made and shown but not used by another task. Client signing is shown by the self-test. -11. The terminal and the vault are not restarted if they die. The root task is trusted. +11. Supervision of the terminal and the vault is polling by the root task, which is trusted and is itself not supervised. The end of a service is seen up to two ticks late. A service that hangs without ending is not noticed. A service is started again at most 3 times per boot, and a vault that is started again has no key. No committed test makes the real terminal or the real vault end during service: the waits, the budget of 3 and the end of supervision are covered only by host tests of `k0-sup` with a mock, and the boot self-test runs retire, erase and rebuild with one restart per service and without waits. The erase of an ended vault is not read back. 12. Terminal output counts against the user share of the in-memory boot log. Once that share is full, later task output is not recorded there. 13. The vault limits under "The signing oracle" all stay. Nothing ran on real hardware. @@ -280,14 +284,14 @@ What the oracle does not claim: 1. The algorithm is Ed25519 (PureEdDSA with SHA-512, as in FIPS 186-5 and RFC 8032). The implementation is the vendored crate `ed25519-dalek` 2.2.0 and has no validation of any kind. The key does not come from an approved random bit generator. 2. There is no side-channel analysis of the crate on this kernel. -3. There is one key per boot (a second KEYGEN is refused with `key-exists`, and after ZEROIZE a reboot is needed), no persistence, no key import or export and no DRBG. The only operator input is the serial terminal, which has no authentication (see "Serial input and the operator terminal"). No post-quantum algorithm exists yet. +3. There is one key per boot (a second KEYGEN is refused with `key-exists`, and after ZEROIZE a reboot is needed), no persistence, no key import or export and no DRBG. The key does not survive the end of the vault task either: the root task erases the memory of a service vault that ended, and the vault it starts in its place has no seed and no key (see "Serial input and the operator terminal"). The only operator input is the serial terminal, which has no authentication (see "Serial input and the operator terminal"). No post-quantum algorithm exists yet. 4. All signers share the one key, so a signature carries no client identity. 5. Availability of the vault is not protected. Clients share one endpoint and must use timeouts, and the operator can erase the key. 6. The root task is trusted and could read the vault. 7. The oracle was only run in QEMU (TCG and HVF). The scrubs of stack copies (kernel boot stack, vault stack after signing) are best effort. 8. The self-test runs its clients one after another in one client address space, so it shows isolation between the vault and a client, not between clients. It makes its key from the public RFC 8032 test seed, with the real seed information, so the entropy rule is still exercised. -Seed and key: the vault has the states `fresh`, `seeded`, `ready`, `zeroized` and `failed`. INIT (admin only, once) only delivers the seed. The vault checks the entropy rule and holds the seed (`seeded`). KEYGEN (admin and operator) makes the key from the held seed with the chosen algorithm and wipes the seed (`ready`). A vault in an image without an algorithm refuses the seed and stays `fresh`, and an all-zero seed is refused. +Seed and key: the vault has the states `fresh`, `seeded`, `ready`, `zeroized` and `failed`. INIT (admin only, once) only delivers the seed. The vault checks the entropy rule and holds the seed (`seeded`). KEYGEN (admin and operator) makes the key from the held seed with the chosen algorithm and wipes the seed (`ready`). A vault in an image without an algorithm refuses the seed and stays `fresh`, and an all-zero seed is refused. A vault that the root task starts again after the vault task ended begins in `zeroized` and refuses INIT, so it never holds a seed or a key. Entropy rule: the vault refuses the boot seed (status `NO_ENTROPY`) unless the boot seed contains at least 32 bytes of `rng-seed` or 256 bits from RNDR. QEMU virt provides a 32-byte `rng-seed`. Every reply carries indicator bits: the algorithm is in FIPS 186-5, the self-tests passed, at least 32 `rng-seed` bytes went into the key seed, and RNDR went into the key seed. These bits report what happened. They are not a validation claim. The STATUS reply packs the state, the key's algorithm and the algorithms in the image into one word. diff --git a/SECURITY_KR.md b/SECURITY_KR.md index 128a341..329861d 100644 --- a/SECURITY_KR.md +++ b/SECURITY_KR.md @@ -56,8 +56,10 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다. - **바인딩**: 두 바인딩은 모두 태스크의 TCB 안에 케이퍼빌리티로 보관됩니다. 둘 중 하나가 revoke되거나 삭제되면 그 태스크는 해체됩니다. - **격리의 범위**: 격리는 서로 다른 CNode와 주소 공간에 묶인 태스크 사이에서 성립합니다. 루트 태스크의 보조 스레드처럼 같은 것을 함께 사용하는 태스크끼리는 서로의 스레드입니다. 태스크의 TCB, CNode, AddrSpace 케이퍼빌리티를 가진 쪽이 그 태스크를 통제합니다. - **권한**: 케이퍼빌리티는 권한(R, W, X)을 가집니다. 권한은 `CAP_COPY`로 줄이기만 할 수 있고 늘릴 수는 없습니다. `Endpoint` 케이퍼빌리티는 `CAP_COPY`로 한 번 설정하는 배지를 가질 수 있고, 수신자가 이 배지를 받습니다. `Console` 케이퍼빌리티도 같은 방식으로 R(입력 읽기)과 W(출력 쓰기) 권한을 가집니다. retype된 프레임은 X를 얻을 수 없고 X는 루트 태스크의 text 프레임에만 있으므로, 어떤 물리 프레임도 한 곳에서 쓰기 가능하면서 다른 곳에서 실행 가능하지 않습니다. -- **파생과 해체**: 케이퍼빌리티는 파생 목록을 이룹니다. `CAP_REVOKE`는 파생된 모든 케이퍼빌리티를 제거하고, `CAP_DELETE`는 슬롯까지 제거합니다. 오브젝트는 원본 케이퍼빌리티가 제거될 때 finalize되며, 그 뒤 해당 `Untyped` 메모리를 다시 retype할 수 있습니다. retype된 오브젝트는 케이퍼빌리티가 만들어지기 전에 0으로 지워집니다. +- **파생과 해체**: 케이퍼빌리티는 파생 목록을 이룹니다. `CAP_REVOKE`는 파생된 모든 케이퍼빌리티를 제거하고, `CAP_DELETE`는 슬롯까지 제거합니다. 오브젝트는 원본 케이퍼빌리티가 제거될 때 finalize되며, 그 뒤 해당 `Untyped` 메모리를 다시 retype할 수 있습니다. retype된 오브젝트는 케이퍼빌리티가 만들어지기 전에 0으로 지워집니다. `CAP_REVOKE`와 `CAP_DELETE` 자체는 풀어 준 메모리를 0으로 지우지 않습니다. 그래뉼은 `RETYPE`이 그것으로 다시 오브젝트를 만들 때 0으로 지워집니다. +- **메모리 예산**: `UNTYPED_SPLIT`(시스템 콜 19번)은 `Untyped` 케이퍼빌리티에서 더 작은 `Untyped` 케이퍼빌리티, 곧 주어진 그래뉼 수만큼의 자식을 잘라냅니다. 모든 오브젝트는 1 그래뉼이므로, n 그래뉼짜리 자식만 가진 태스크는 거기서 오브젝트를 정확히 n개 얻고 더는 얻지 못합니다. 자식은 복사할 수 없고, 다른 태스크의 CNode로 옮길 수 있으며, 다시 분할할 수 있습니다. 부모를 회수하면 자식과 자식에서 만든 것이 전부 제거됩니다. 자식을 회수하면 메모리는 부모가 아니라 자식에게 돌아갑니다. 규칙은 [design/kr/capabilities_KR.md](design/kr/capabilities_KR.md#untyped-분할)에 있습니다. 자식이 제한하지 않는 것은 아래 "가용성"에 적었습니다. - **폴트 격리**: 격리된 태스크의 폴트, 종료, 알 수 없는 시스템 콜은 그 태스크만 종료시킵니다. +- **태스크 상태**: `TCB_STATUS`(시스템 콜 20번)는 `Tcb` 케이퍼빌리티를 가진 쪽에게 그 태스크가 시작 전인지, 살아 있는지, 끝났는지 알려 줍니다. 아무것도 바꾸지 않고 끝난 이유를 알려 주지 않습니다. `Tcb` 케이퍼빌리티에는 권한이 없으므로 그것을 가진 쪽은 누구나 물을 수 있습니다. 커널이 스스로 누구에게 알리지는 않습니다. `main`에서도 **여전히 제공하지 않는 것**은 다음과 같습니다. @@ -69,11 +71,11 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다. - 실시간이나 지연 시간에 대한 약속은 없습니다. 커널은 선점되지 않고 틱은 1초입니다. 자기보다 먼저 실행될 태스크가 k개(실행 중인 태스크 포함)일 때 준비된 태스크는 이제 k + 1 틱 주기 안에 시작하며, 전에는 k 주기 안에 시작했으므로 대기가 최대 한 틱 길어질 수 있습니다. CPU를 쓰는 태스크 하나 뒤에서 호출과 응답을 주고받는 호출자와 서버는 모델에서 왕복당 2틱이 걸렸고 이제는 4틱이 걸립니다. 한 번에 한 주기에서 두 주기를 실행한다는 것과 k + 1 주기를 기다린다는 수치는 이 버전의 스케줄러를 설명할 뿐 인터페이스가 아닙니다. - 커널은 더 이상 태스크의 진입 종류를 고르지 않습니다. 커널은 사건의 이름만 알리고, 호스트에서 테스트하는 코드 한 곳(`crates/k0-part`)이 진입 종류를 고릅니다. 그래서 실제 커널에 대한 어떤 테스트로도 발견되지 않던 세 가지 실수(틱 자신의 전환, 대기 루프가 틱에 대해 하는 보고, 루트 태스크로 넘기는 시점의 진입 종류)는 이제 그 코드의 호스트 테스트가 다룹니다. 지금 어떤 테스트도 보지 못하는 것은 "고정 시간 분할" 절에 나열했습니다. 보호 구간, EL0로 돌아가기 전의 대기, 도메인이 바뀔 때의 TLB 비우기, 표가 있을 때의 콘솔 규칙입니다. 그 코드를 둘러싼 큐와 기한 목록(`crates/k0-sched`, `crates/k0-ipc`)에는 호스트 테스트가 없으며, 부팅 테스트와 리뷰로 확인합니다. - 측정에 쓴 공격자는 루트 태스크가 잰 루프 횟수로 양보 시점을 미리 맞춰 준 공격자입니다. 공격자가 그 시점을 스스로 찾는 데 무엇이 필요한지는 측정하지 않았습니다. 모든 실행은 QEMU(TCG와 HVF)에서 했고 하드웨어에서는 실행하지 않았습니다. - - 커널은 선점되지 않습니다. 긴 시스템 콜(예: 오브젝트가 많은 `Untyped`에 대한 `CAP_REVOKE`)은 다른 모든 태스크와 모든 타임아웃을 지연시킵니다. `Untyped` 케이퍼빌리티는 나누거나 상한을 걸 수 없으므로, 이것을 받은 태스크는 그 전체로 이 일을 할 수 있습니다. `Untyped`는 시스템 전체의 가용성을 맡길 수 있는 태스크에만 넘기세요. 루트 태스크는 터미널과 볼트에 `Untyped`를 주지 않습니다. + - 커널은 선점되지 않습니다. 긴 시스템 콜(예: 오브젝트가 많은 `Untyped`에 대한 `CAP_REVOKE`)은 다른 모든 태스크와 모든 타임아웃을 지연시킵니다. `Untyped` 케이퍼빌리티는 분할할 수 있고, 다른 `Untyped`를 갖지 않은 태스크에 준 자식 `Untyped`는 두 가지를 제한합니다. 그 태스크가 쓸 수 있는 메모리의 양, 그리고 그에 따라 한 번에 가질 수 있는 오브젝트의 수입니다. 시간은 제한하지 않습니다. `CAP_REVOKE`와 `CAP_DELETE`는 여전히 인터럽트를 마스크한 채 제거하는 케이퍼빌리티 수(복사본 포함)에 비례하는 시간이 걸리고, 중간에 끊었다가 이어서 할 수 있는 회수는 아직 없습니다. 그래서 자식을 포함해 어떤 `Untyped`든 받은 태스크는 여전히 모두를 지연시킬 수 있습니다. `Untyped`는 시스템 전체의 가용성을 맡길 수 있는 태스크에만 넘기세요. 루트 태스크는 터미널과 볼트에 `Untyped`를 주지 않습니다. 둘을 만드는 슬랩은 루트 태스크의 CNode에 남아 있습니다. - `k0_arch::fatal`이나 커널 패닉은 여전히 기계를 멈추며, EL0에서 발생한 SError도 마찬가지입니다. - 폴트 및 종료 줄로 부트 로그의 커널 부분을 채우는 문제는 `main`에서 대응했습니다. 태스크가 끝날 때 커널이 내는 줄(폴트, 종료, 알 수 없는 시스템 콜)은 이제 로그에서 자기 몫 4 KiB만 쓰고, 커널용으로 남겨 둔 마지막 2 KiB 앞에서 멈춥니다. 커널은 이 사실을 한 번 알립니다(`k0: task lines over the log quota, later ones go to the console only`). 몫을 넘긴 줄은 콘솔에만 나가므로 콘솔 드라이버가 없는 이미지에서는 사라집니다. 이것이 지키는 것은 커널 자신의 줄과 그 마지막 부분입니다. 몫 하나를 모든 태스크가 나눠 쓰므로, 태스크를 만들 수 있는 태스크는 여전히 다른 태스크의 폴트 줄과 종료 줄을 로그에서 밀어낼 수 있습니다. 터미널과 볼트가 든 이미지의 부팅은 이 몫의 4분의 1쯤을 씁니다. - **커널 자원 고갈**: 커널은 부팅할 때 `Untyped`로 내주는 메모리가 필요로 할 수 있는 페이지 테이블과 주소 공간 레지스트리 항목을 각 범위의 끝에서 떼어 미리 확보합니다. 따라서 `RETYPE`가 페이지 테이블 부족으로 `KERNEL_RESOURCE`와 함께 실패하는 일은 없고, 주소 공간의 수는 메모리로만 제한됩니다. 이 예약분은 4 KiB 그래뉼에서 RAM의 약 0.4 %입니다(페이지 테이블과 등록 항목이 각각 약 0.2 %). 자기 예약분을 담기에 너무 작은 범위는 `Untyped`로 내주지 않고, 온전한 페이지가 하나도 없는 범위도 내주지 않습니다. -- **미구현 기능**: 핸들러 태스크로의 폴트 전달, 알림(notification), IPC를 통한 케이퍼빌리티 전송이 아직 없습니다. +- **미구현 기능**: 핸들러 태스크로의 폴트 전달, 알림(notification), IPC를 통한 케이퍼빌리티 전송이 아직 없습니다. 태스크가 다른 태스크가 끝났다는 것을 아는 방법은 `TCB_STATUS`로 묻는 것뿐이며, 여기에는 `Tcb` 케이퍼빌리티가 필요하고 이유는 알 수 없습니다. - **EL0에서 보이는 시간**: EL0는 여전히 하드웨어 카운터나 타이머를 읽을 수 없습니다. IPC 타임아웃은 태스크에 스케줄러 틱(1초)만큼 거친 시계와 타이머 인터럽트에 맞춰진 깨어남을 제공합니다. 이것이 캐시나 추측 실행 공격에 쓸 만한 시간 원천으로 증폭될 수 있는지는 분석하지 않았습니다. - **revoke 뒤의 송신자**: 엔드포인트에 이미 대기 중인 송신자는 케이퍼빌리티가 revoke된 뒤에도 한 번 전달됩니다. - **직렬 회선**: feature `console-input` 또는 `terminal`을 포함해 빌드한 이미지에서는 외부 당사자가 직렬 회선으로 커널에 닿을 수 있습니다. 운영자 터미널에는 인증이 없고, 외부 당사자가 태스크 실행 중에 인터럽트를 일으킬 수 있으며, 입력은 실행 중인 태스크 뒤에서 기다립니다("직렬 입력과 운영자 터미널" 참고). @@ -85,7 +87,7 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다. - **출력의 출처**: 커널 출력과 태스크 출력은 부트 로그 하나를 함께 사용합니다. 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔 하나도 함께 사용합니다. 줄에는 누가 썼는지 표시가 없습니다. 쓰기 권한이 있는 `Console` 케이퍼빌리티를 가진 태스크는 `k0:`로 시작하는 줄을 출력할 수 있습니다. 커널은 제어 바이트를 바꾸고 태스크 출력이 부트 로그에서 차지할 수 있는 양을 제한합니다. 그래도 콘솔이나 로그를 읽는 쪽은 `tools/qemu-boot-test.sh`를 포함해 누구도 `k0: entering root task (el0)` 뒤에 나온 `k0:` 줄을 커널이 쓴 것으로 믿을 수 없습니다. `k0: console drivers [...]` 줄도 여기에 포함됩니다("선택적 콘솔 출력" 참고). - **EL2 트랩**: 격리는 기밀성과 무결성을 다루고 가용성은 다루지 않습니다. 커널이 EL1로 내려온 뒤 EL2로 트랩이 오면 설계상 기계 전체를 멈춥니다. - **EL2 진입**: EL2 진입은 Linux와 같은 펌웨어 약속을 전제로 합니다. EL3 펌웨어는 세분화된 트랩과 HCRX 제어 기능이 있으면 이를 켜 주어야 합니다. -- **루트 태스크**: 루트 태스크는 여전히 신뢰 대상이며 최초의 `Untyped` 케이퍼빌리티를 가지고, `write_bootinfo`는 그 물리 주소를 루트 태스크에 계속 노출합니다. 루트 태스크는 시간 분할의 제어 케이퍼빌리티도 가지며, 자가 테스트의 끝에서 이를 삭제할 때까지 가집니다. 서명 오라클이 있는 이미지에서는 루트 태스크가 볼트도 만들며 볼트의 메모리를 읽을 수 있습니다("서명 오라클" 참고). feature `terminal`이 있는 이미지에서는 터미널 태스크도 시작하며, 터미널이나 볼트가 죽어도 다시 시작하지 않습니다. +- **루트 태스크**: 루트 태스크는 여전히 신뢰 대상이며 최초의 `Untyped` 케이퍼빌리티를 가지고, `write_bootinfo`는 그 물리 주소를 루트 태스크에 계속 노출합니다. 루트 태스크는 시간 분할의 제어 케이퍼빌리티도 가지며, 자가 테스트의 끝에서 이를 삭제할 때까지 가집니다. 서명 오라클이 있는 이미지에서는 루트 태스크가 볼트도 만들며 볼트의 메모리를 읽을 수 있습니다("서명 오라클" 참고). feature `terminal`이 있는 이미지에서는 터미널 태스크도 시작하며 터미널과 볼트를 감독합니다("직렬 입력과 운영자 터미널" 참고). 루트 태스크 자신을 감독하는 것은 없습니다. > [!WARNING] > `main`에서도 신뢰하지 않는 코드의 실행은 실험적인 것으로 취급하세요. 위의 가용성 한계는 그대로 적용됩니다. @@ -241,7 +243,9 @@ $ grep -a 'k0: console drivers' <이미지 파일> 터미널의 정체는 다음과 같습니다. - **격리**: 터미널은 자기 주소 공간을 가진 태스크이며 케이퍼빌리티를 두 개 가집니다. R과 W가 있는 `Console` 사본, 그리고 송신 권한과 운영자 배지가 있는 볼트 엔드포인트입니다. 볼트의 응답 프레임은 터미널에 읽기 전용으로 매핑됩니다. -- **시작**: 자가 시험이 끝나면 루트 태스크가 새 볼트를 시작하고 부트 시드를 넘기며, 터미널과 똑같이 연결한 적대적 태스크 둘을 실행하고(거부되어 폴트로 끝나야 합니다), 자신의 admin 케이퍼빌리티를 버리고, 터미널을 시작한 뒤 영원히 블록됩니다. `root: terminal wiring holds`와 `root: service started` 줄이 이를 보고합니다. 입력 경로가 없는 기계에서는 루트 태스크가 `root: no console input, terminal not started`를 출력합니다. +- **시작**: 자가 시험이 끝나면 볼트가 있는 이미지의 루트 태스크는 시드를 받지 않는 볼트로 볼트의 재시작 경로를 시험한 뒤, 새 볼트를 시작하고 부트 시드를 넘깁니다. 그다음 모든 터미널 이미지에서 터미널과 똑같이 연결한 적대적 태스크 둘을 실행하고(거부되어 폴트로 끝나야 합니다), 자신의 admin 케이퍼빌리티를 버리고, 터미널을 시작합니다. `root: vault restart test pass`, `root: terminal wiring holds`, `root: terminal restart test pass`, `root: service started` 줄이 이를 보고합니다. 입력 경로가 없는 기계에서는 루트 태스크가 `root: no console input, terminal not started`를 출력합니다. +- **감독**: `root: service started` 뒤에 루트 태스크는 영원히 블록되지 않습니다. 두 번째 틱마다 `TCB_STATUS`로 터미널 태스크와 볼트 태스크가 끝났는지 커널에 묻습니다. 루트 태스크는 자기만 가진 엔드포인트에서만 기다리므로 서비스가 루트 태스크를 붙잡아 둘 수 없습니다. 서비스마다 자기 슬랩에서 만들어지며, 슬랩은 루트 태스크의 CNode에 남는 16 그래뉼짜리 자식 `Untyped`입니다. 서비스가 끝나면 루트 태스크가 슬랩을 회수해 그 서비스를 이루던 것을 전부 제거하고, 같은 슬랩과 같은 슬롯에 서비스를 다시 만듭니다. 서비스는 부팅당 최대 3번, 적어도 2, 8, 32틱을 기다린 뒤에 다시 시작하며 한도는 다시 채워지지 않습니다. 콘솔 입력 경로가 없는 기계에서는 터미널을 다시 시작하지 않습니다. 터미널이 완전히 내려가면 아직 올라와 있는 볼트를 멈추고 지웁니다. 정책은 크레이트 `userspace/k0-sup`이며, `unsafe` 코드와 의존성이 없고 호스트에서 시험합니다. 자세한 내용과 로그 줄은 [design/kr/terminal_KR.md](design/kr/terminal_KR.md#감독)에 있습니다. +- **끝난 볼트 지우기**: 끝난 볼트의 슬랩을 다른 것에 쓰기 전에, 루트 태스크는 슬랩의 16 그래뉼 전부를 프레임으로 retype해서 하나하나 0으로 지우고, 17번째 `RETYPE`이 `EXHAUSTED`를 반환하기를 요구합니다. operator 응답 프레임도 0으로 지웁니다. **다시 시작한 볼트에는 시드도 키도 없고 INIT을 거부합니다**. 부트 시드는 한 번 쓰였고 남아 있지 않기 때문입니다. 볼트를 다시 시작한 뒤에는 기계를 다시 부팅할 때까지 키가 없습니다. - **입력 규칙**: 한 줄은 출력 가능한 ASCII 최대 64자입니다. 터미널은 프롬프트 전에 UART에 닿은 것을 버리고, 보고된 손실은 다음 줄 끝까지의 모든 것을 버립니다(`err input-lost`). 한계는 다음과 같습니다. @@ -256,7 +260,7 @@ $ grep -a 'k0: console drivers' <이미지 파일> 8. 운영자가 입력하는 동안 커널 줄이 나타나면 화면의 줄은 쪼개지지만 버퍼는 온전하며, Enter는 버퍼 전체를 실행합니다. 9. `Console` 출력이 있는 모든 태스크는 여전히 커널 줄이나 루트 태스크 줄처럼 보이는 줄을 출력할 수 있으며, 접두어를 인증하는 것은 없습니다. 터미널은 추가로 자기 현재 줄 안에서 지울 수 있습니다. 10. 서비스 모드에는 서명 클라이언트가 없습니다. 볼트의 키는 만들어지고 표시되지만 다른 태스크가 사용하지 않습니다. 클라이언트의 서명은 자가 시험이 보여 줍니다. -11. 터미널과 볼트는 죽어도 다시 시작하지 않습니다. 루트 태스크는 신뢰 대상입니다. +11. 터미널과 볼트의 감독은 루트 태스크의 폴이며, 루트 태스크는 신뢰 대상이고 그 자신은 감독받지 않습니다. 서비스가 끝난 것은 최대 두 틱 늦게 알게 됩니다. 끝나지 않은 채 멈춰 있는 서비스는 알아채지 못합니다. 서비스는 부팅당 최대 3번 다시 시작하고, 다시 시작한 볼트에는 키가 없습니다. 커밋된 시험 가운데 서비스 중에 실제 터미널이나 실제 볼트를 끝내는 것은 없습니다. 대기, 3번이라는 한도, 감독의 끝은 모형을 쓰는 `k0-sup`의 호스트 시험만 다루고, 부팅 자가 시험은 걷어 내기, 지우기, 다시 만들기를 서비스마다 재시작 한 번으로, 대기 없이 실행합니다. 끝난 볼트의 소거는 다시 읽어 확인하지 않습니다. 12. 터미널 출력은 메모리 안 부트 로그의 사용자 몫에 포함됩니다. 그 몫이 차면 이후 태스크 출력은 거기에 기록되지 않습니다. 13. "서명 오라클"의 볼트 한계는 모두 그대로입니다. 실제 하드웨어에서 실행한 것은 없습니다. @@ -280,14 +284,14 @@ $ grep -a 'k0: console drivers' <이미지 파일> 1. 알고리즘은 Ed25519(SHA-512를 쓰는 PureEdDSA, FIPS 186-5와 RFC 8032에 있음)입니다. 구현은 벤더링한 크레이트 `ed25519-dalek` 2.2.0이며 어떤 종류의 검증도 받지 않았습니다. 키는 승인된 난수 비트 생성기에서 나오지 않습니다. 2. 이 커널 위에서 크레이트의 부채널 분석은 하지 않았습니다. -3. 키는 부팅마다 하나이고(두 번째 KEYGEN은 `key-exists`로 거부하며, ZEROIZE 뒤에는 재부팅이 필요합니다), 영속성, 키 가져오기·내보내기, DRBG가 없습니다. 운영자 입력은 인증이 없는 직렬 터미널뿐입니다("직렬 입력과 운영자 터미널" 참고). 양자 내성 알고리즘은 아직 없습니다. +3. 키는 부팅마다 하나이고(두 번째 KEYGEN은 `key-exists`로 거부하며, ZEROIZE 뒤에는 재부팅이 필요합니다), 영속성, 키 가져오기·내보내기, DRBG가 없습니다. 키는 볼트 태스크가 끝나도 남지 않습니다. 루트 태스크가 끝난 서비스 볼트의 메모리를 지우고, 그 자리에 시작하는 볼트에는 시드도 키도 없습니다("직렬 입력과 운영자 터미널" 참고). 운영자 입력은 인증이 없는 직렬 터미널뿐입니다("직렬 입력과 운영자 터미널" 참고). 양자 내성 알고리즘은 아직 없습니다. 4. 모든 signer가 키 하나를 공유하므로 서명에는 클라이언트 신원이 담기지 않습니다. 5. 볼트의 가용성은 보호하지 않습니다. 클라이언트는 엔드포인트 하나를 공유하며 타임아웃을 사용해야 하고, 운영자는 키를 지울 수 있습니다. 6. 루트 태스크는 신뢰 대상이며 볼트를 읽을 수 있습니다. 7. 오라클은 QEMU(TCG와 HVF)에서만 실행했습니다. 스택 사본(커널 부트 스택, 서명 뒤의 볼트 스택)의 삭제는 최선을 다하는 수준입니다. 8. 자가 시험은 클라이언트를 하나의 클라이언트 주소 공간에서 차례로 실행하므로, 클라이언트 사이가 아니라 볼트와 클라이언트 사이의 격리를 보여 줍니다. 자가 시험은 공개된 RFC 8032 테스트 시드로 키를 만들며, 실제 시드 정보를 함께 넘기므로 엔트로피 규칙은 여전히 시험됩니다. -시드와 키는 다음과 같습니다. 볼트의 상태는 `fresh`, `seeded`, `ready`, `zeroized`, `failed`입니다. INIT(admin 전용, 한 번)은 시드를 전달하기만 합니다. 볼트는 엔트로피 규칙을 확인하고 시드를 보관합니다(`seeded`). KEYGEN(admin과 operator)은 보관한 시드에서 선택한 알고리즘으로 키를 만들고 시드를 지웁니다(`ready`). 알고리즘이 없는 이미지의 볼트는 시드를 거부하고 `fresh`에 머물며, 모두 0인 시드도 거부합니다. +시드와 키는 다음과 같습니다. 볼트의 상태는 `fresh`, `seeded`, `ready`, `zeroized`, `failed`입니다. INIT(admin 전용, 한 번)은 시드를 전달하기만 합니다. 볼트는 엔트로피 규칙을 확인하고 시드를 보관합니다(`seeded`). KEYGEN(admin과 operator)은 보관한 시드에서 선택한 알고리즘으로 키를 만들고 시드를 지웁니다(`ready`). 알고리즘이 없는 이미지의 볼트는 시드를 거부하고 `fresh`에 머물며, 모두 0인 시드도 거부합니다. 볼트 태스크가 끝난 뒤 루트 태스크가 다시 시작한 볼트는 `zeroized`에서 시작하고 INIT을 거부하므로, 시드도 키도 가지는 일이 없습니다. 엔트로피 규칙은 다음과 같습니다. 볼트는 부트 시드에 `rng-seed` 바이트가 32바이트 이상 있거나 RNDR에서 온 256비트가 있지 않으면 부트 시드를 거부합니다(상태 `NO_ENTROPY`). QEMU virt는 32바이트 `rng-seed`를 제공합니다. 모든 응답에는 표시 비트가 담깁니다. 알고리즘이 FIPS 186-5에 있는지, 자가 시험이 통과했는지, `rng-seed`가 32바이트 이상 키 시드에 들어갔는지, RNDR이 키 시드에 들어갔는지입니다. 이 비트는 일어난 일을 보고할 뿐 검증 주장이 아닙니다. STATUS 응답은 상태, 키의 알고리즘, 이미지에 있는 알고리즘을 한 워드에 담습니다. diff --git a/USAGE.md b/USAGE.md index b871ed3..6729d79 100644 --- a/USAGE.md +++ b/USAGE.md @@ -89,7 +89,9 @@ The following table lists the lines that an image with a console driver prints, | `k0: task fault ...` and `k0: unknown syscall 65535, killing task` | Rule violations that the tests cause on purpose. Each one stops only the task that broke the rule. A normal run has exactly 6 `k0: task fault` lines and 1 `k0: unknown syscall` line. An image built with a `vault` feature has 8 `k0: task fault` lines | | `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 + 130124 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, the share could not be mapped, or the range holds no whole page, so the kernel did not hand the range out. The boot continues. A normal run on QEMU virt does not print it | +| `root: tcb status tests pass` | The call that tells whether a task has not started, is alive or has ended (`TCB_STATUS`) gave the right answer for tasks in each of these states. It comes after `root: fault isolation tests pass` | | `root: timeout tests pass` | The self-tests of IPC timeouts passed | +| `root: untyped split tests pass` | A task that was given a budget of 8 granules of memory, cut out of a larger block with `UNTYPED_SPLIT`, got exactly 8 objects from it. The block was then taken back, used again from its start, and the frames read from it were zero. It comes after `root: timeout tests pass` | | `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: partition refusal pass` | The two system calls of the time partitions refused every wrong request (a wrong capability, a malformed table, a table without the caller's domain, a domain out of range, a task that has already run, a copy of the control capability) | @@ -220,7 +222,7 @@ $ cargo run -p k0-kernel --features console,terminal,vault-ed25519 `cargo run` starts QEMU with the serial port on your terminal. QEMU's own escape key is `Ctrl-A` there (`Ctrl-A`, then `X` quits QEMU), so `Ctrl-A` never reaches K0. -After the self-tests, the root task starts the vault, hands it the boot seed, runs two hostile tasks wired like the terminal (they must be refused and end in a fault), drops its admin capability and starts the terminal. The boot log shows `root: vault seeded`, `root: terminal console filter [...]`, `root: terminal wiring holds`, two `k0: task fault` lines, `root: service started` and then the banner. On a machine without an input path it shows `root: no console input, terminal not started`. After the first read, the periodic `k0: tick N` lines stop, and one line `k0: tick lines off (console input in use)` marks that. In the following session, every command ends with exactly one line, `ok` or `err `: +After the self-tests, the root task tries out how it would start the vault again, starts the vault, hands it the boot seed, runs two hostile tasks wired like the terminal (they must be refused and end in a fault), drops its admin capability and starts the terminal. The boot log shows `root: vault restart test pass`, `root: vault seeded`, `root: terminal console filter [...]`, `root: terminal wiring holds`, two `k0: task fault` lines, `root: terminal restart test pass`, `root: service started` and then the banner. After that the root task prints nothing more as long as the terminal and the vault keep running (see "When the terminal or the vault ends" below). On a machine without an input path it shows `root: no console input, terminal not started`. After the first read, the periodic `k0: tick N` lines stop, and one line `k0: tick lines off (console input in use)` marks that. In the following session, every command ends with exactly one line, `ok` or `err `: ``` K0 operator console, type 'help' @@ -296,12 +298,44 @@ What stays true, and what is not covered: - **Hardware**: a 16550 console has no input. The SBSA UART path, FIFO overruns and the receive timeout interrupt are not exercised by QEMU, only by host tests with a fake UART. The cut-off for an interrupt line that fires without a UART cause is also covered only by host tests. No test measures kernel time under a flood on a machine. Nothing ran on real hardware. - **Screen**: if a kernel line appears while you are typing, the screen line is split but the buffer is whole, and Enter runs the whole buffer. Any task with `Console` output can still print lines that look like kernel or root task lines, and nothing authenticates the prefix. The terminal can additionally erase within its current line. - **Bytes held back**: "dropped before the prompt" counts bytes that reached the UART. An emulator or adapter that holds bytes back delivers them later (QEMU does). -- **Service**: no signing client exists in service mode yet. The key is made and shown but not used by another task. The terminal and the vault are not restarted if they die. The root task is trusted. +- **Service**: no signing client exists in service mode yet. The key is made and shown but not used by another task. The root task starts the terminal and the vault again when they end, at most 3 times each per boot, and a vault that is started again has no key (see "When the terminal or the vault ends" below). The root task is trusted. - **Boot log**: terminal output counts against the user share of the in-memory boot log. Once that share is full, later task output is not recorded there. - **Vault**: all earlier limits stay. The implementation is unvalidated, there is no side-channel analysis, the key does not come from an approved random bit generator, there is no persistence and there is no PQC. The availability of the vault and of the terminal is not protected. If the console interrupt number is wrong, only the input path is lost: the boot log shows `k0: console input off (...)`. The reasons are `no console`, `no receive driver for this uart`, `no usable interrupt in the device tree`, `register frame too small`, `console not attached`, `interrupt number out of range` and `interrupt not available`. A line that keeps firing without a UART cause is switched off after 8 entries with `k0: console input off (interrupt N fired without a uart cause)`. With input on, the boot log shows `k0: console input on (pl011 irq 33)`. The interrupt number is part of the platform line (`k0: platform con=pl011@0x9000000,irq33 ...`), so a `K0_PIN` made before this change no longer matches and must be made again. +### When the terminal or the vault ends + +In a terminal image the root task watches the terminal and the vault. Every second tick, which is every 2 seconds, it asks the kernel whether the two tasks are still alive. A healthy session shows no line from it. When a task has ended, for example after a fault, the root task takes back the memory the task was built from and starts the service again in the same place. It does this at most 3 times per service per boot, and each time it waits longer first: at least 2, then 8, then 32 ticks. + +The following table lists the lines the root task can print after `root: service started`, and what each means for you. + +| Line | Meaning | +| --- | --- | +| `root: terminal ended, restart 1 of 3 after at least 2 ticks` | The terminal task ended. It comes back after the wait. The numbers go up to `restart 3 of 3 after at least 32 ticks` | +| `root: terminal started again` | A new terminal task runs. The banner and the prompt appear again, and what you were typing is gone | +| `root: vault ended and erased, restart 1 of 3 after at least 2 ticks` | The vault task ended and its memory was erased. A vault comes back after the wait, without a key | +| `root: vault started again without a key` | A new vault task runs. It has no seed and no key and cannot get one. `vault status` shows `state=zeroized` | +| `root: terminal ended, no console input, not started again` | The terminal ended and the kernel has no console input path, so a new terminal could read nothing | +| `root: terminal ended, restart budget spent, not started again` | The terminal ended after its third restart. It stays down until you reboot | +| `root: vault ended and erased, restart budget spent, not started again` | The vault ended after its third restart. It stays down until you reboot | +| `root: vault stopped and erased, no terminal` | The terminal is down for good, so the root task stopped the vault and erased its memory | +| `root: vault ended and erased, no terminal, not started again` | The vault was waiting to be started again when the terminal went down for good | +| `root: supervision over` | No service is left. Reboot to get the terminal back | + +> [!IMPORTANT] +> A vault that was started again has no key, and no key can be made until the machine is booted again. The boot seed was given to the first vault once, and the root task keeps no copy of it. + +With `vault-ed25519`, `vault keygen ed25519` and `vault pubkey` answer `err zeroized` on such a vault. While no vault is running, a vault command that no vault takes within 5 ticks answers `err vault-timeout`. + +What this does not cover: + +- **A task that hangs**: the root task notices only a task that ended. A terminal or a vault that hangs without ending looks alive to it. +- **The root task itself**: it is trusted, and nothing watches it. If one of its own checks fails while it runs the services, it prints `root: FAIL ...`, tries to erase the vault's memory (`root: vault erased before exit` or `root: vault not erased`) and exits. +- **Tests**: no test makes the real terminal or the real vault end during a session. The waits and the limit of 3 are tested on the host with a stand-in for the kernel, and every boot of a terminal image tries one restart per service, without waits (`root: vault restart test pass`, `root: terminal restart test pass`). + +The design is described in [design/en/terminal.md](design/en/terminal.md#supervision). + ## Booting through UEFI UEFI is the standard way for firmware to start a program on many computers. The firmware loads a program file with the ending `.efi` from a disk, runs it, and describes the machine to it. A loader is a small program that does this one job: it prepares the machine and then starts another program. K0 has its own UEFI loader, `crates/k0-efi` and `loader/`. It carries the kernel inside itself, so the one `.efi` file is all the firmware needs. The kernel does not change and boots the same way as without UEFI. The following picture shows the path of a UEFI boot. @@ -413,7 +447,7 @@ $ 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 415 host tests (327 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 415 are 15 (`k0-abi`), 54 (`k0-cap`), 85 (`k0-boot`), 33 (`k0-efi`), 19 (`k0-conin`), 9 (`k0-slice`, the rule that decides whether a tick cuts the running task, run on a model of the scheduler), 36 (`k0-part`, the scheduler's decisions under a time partition table and the arithmetic of tick instants, including a comparison with the recorded results of a Lean model), 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 44 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 88. +- `tools/host-test.sh` runs the 457 host tests (369 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 457 are 16 (`k0-abi`), 71 (`k0-cap`, of which 17 are about splitting untyped memory), 85 (`k0-boot`), 33 (`k0-efi`), 19 (`k0-conin`), 9 (`k0-slice`, the rule that decides whether a tick cuts the running task, run on a model of the scheduler), 36 (`k0-part`, the scheduler's decisions under a time partition table and the arithmetic of tick instants, including a comparison with the recorded results of a Lean model), 20 (`k0-sup`, the rules by which the root task starts the terminal and the vault again, run with a stand-in for the kernel), 35 (`k0-vault`, which is 22 with Ed25519 and 13 without), 45 (`k0-term`, which is 24 with the vault feature and 21 without) and 44 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 88. - `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 time partition test adds about 15 seconds, because it lets a table of 9 ticks run one round, so a boot test now takes about 25 seconds. Just before its verdict it also prints `boot-test: partition window retries: N`, the number of times the window test had to run again because the host stalled QEMU. The script does not judge by that number. 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 82 rows on a Mac with HVF and 71 in CI. You can name single rows as arguments. CI runs it. When the window test of a boot row needed its retry, the matrix runs that row once more and fails it if the second run needed the retry too (`matrix: FAIL (the window test needed its retry in two runs)`). @@ -459,7 +493,7 @@ The input and terminal rows check the receive path and the terminal. In the foll | `term-uefi`, `term-uefi-acpi` | The terminal image through the UEFI loader (device tree path and ACPI path) | | `hvf-term` | The terminal image under HVF (Mac only) | -`tools/term-test.py ` boots the image with QEMU's serial port on pipes and runs a scripted session. It covers every command and error, erase and cancel, CR LF, an ESC sequence, a line that is too long, key generation, the public key format, zeroize, 200 kB without a line end, 2000 lines in a row, a serial break and, on QEMU 8.0 or later, a flood of 2000 breaks. `tools/qemu-boot-test.sh` also knows `K0_BOOT_INPUT=on|off` and `K0_BOOT_SERVICE=vault|plain|none` to say what the image should show, and a judge-only mode `K0_BOOT_JUDGE`. A terminal image prints two more `k0: task fault` lines than the same image without the terminal (8 without the vault, 10 with it), so use `K0_BOOT_FAULTS` for it. +`tools/term-test.py ` boots the image with QEMU's serial port on pipes and runs a scripted session. It covers every command and error, erase and cancel, CR LF, an ESC sequence, a line that is too long, key generation, the public key format, zeroize, 200 kB without a line end, 2000 lines in a row, a serial break and, on QEMU 8.0 or later, a flood of 2000 breaks. `tools/qemu-boot-test.sh` also knows `K0_BOOT_INPUT=on|off` and `K0_BOOT_SERVICE=vault|plain|none` to say what the image should show, and a judge-only mode `K0_BOOT_JUDGE`. A terminal image prints two more `k0: task fault` lines than the same image without the terminal (8 without the vault, 10 with it), so use `K0_BOOT_FAULTS` for it. With `K0_BOOT_SERVICE=vault` or `plain` the boot test also expects `root: terminal restart test pass` before `root: service started`, and with `vault` it expects `root: vault restart test pass` before the line about the seed. `tools/term-test.py` fails a session when `root: ` appears in the output after the prompt, because the root task prints there only when the terminal or the vault ended. ### Testing an image without console @@ -542,5 +576,10 @@ The following table lists what to do for each problem. | The screen shows only firmware messages, or the firmware menu | The firmware could not start the loader, or the loader refused and the firmware went on. Look for `k0-loader:` lines. With none, check that the `.efi` file exists and, with `K0_QEMU_ESP`, that the drive is found | | The terminal shows no `k0> ` prompt | Either the image was built without `terminal` (and `console-input`), or the log shows `k0: console input off (...)` or `root: no console input, terminal not started`. Build with `--features console,terminal,vault-ed25519` and read the reason in the boot log | | Nothing happens when I type, or `Ctrl-A` does not arrive | Under `cargo run` QEMU keeps `Ctrl-A` for itself. A 16550 console has no input at all | +| `root: terminal ended, restart ...` appears, and later the banner again | The terminal task ended and the root task started a new one. What you were typing is gone. Look for a `k0: task fault` line before it to see whether the terminal ended in a fault. See "When the terminal or the vault ends" | +| `root: vault ended and erased, ...` or `root: vault started again without a key` appears, or `vault status` shows `state=zeroized` although you did not erase the key | The vault task ended. Its memory was erased, and the vault that was started in its place has no key. Reboot to get a key again | +| A line ends with `not started again`, or `root: supervision over` appears | A service used its 3 restarts, or the terminal ended on a machine without a console input path. The service stays down until you reboot | +| `root: vault erased before exit` or `root: vault not erased` appears | A check of the root task failed while it ran the services. The `root: FAIL ...` line before it names the step. The root task has exited and no longer watches the services | +| `term-test: FAIL kernel line during the session` shows a `root: ` line | The terminal or the vault ended during the scripted session and the root task reported it. That should not happen in a healthy session. Read the log file the script names | | `boot-test` fails on the number of `k0: task fault` lines for a terminal image | That image prints 2 more than without the terminal (8 or 10). Use `K0_BOOT_FAULTS` | | A `K0_PIN` made earlier no longer matches | The platform line now contains the console interrupt (`irq33`). Make the pin again | diff --git a/USAGE_KR.md b/USAGE_KR.md index 43d2784..f755e2d 100644 --- a/USAGE_KR.md +++ b/USAGE_KR.md @@ -89,7 +89,9 @@ $ grep -a 'k0: console drivers' <이미지 파일> | `k0: task fault ...`와 `k0: unknown syscall 65535, killing task` | 테스트가 일부러 일으킨 규칙 위반. 매번 규칙을 어긴 태스크만 멈춤. 정상 실행에서는 `k0: task fault` 줄이 정확히 6개, `k0: unknown syscall` 줄이 1개 나옴. `vault` feature를 포함해 빌드한 이미지에서는 `k0: task fault` 줄이 8개 나옴 | | `k0: kernel reserve tables + address space entries = bytes in ranges` | 커널이 넘겨 주는 메모리 범위마다 맨 위에 자기 페이지 테이블과 주소 공간 목록용 메모리를 따로 떼어 둠. `k0: untyped` 줄보다 먼저 출력됨. QEMU virt 512 MiB에서는 `262 tables + 130124 address space entries = 0x206000 bytes in 3 ranges`로 나오며, 항목 수는 이미지 크기에 따라 달라짐 | | `k0: memory + not handed out ()` | 메모리 범위가 너무 작아 그 예비 몫을 담지 못하거나, 몫을 매핑하지 못하거나, 온전한 페이지가 하나도 없어서 커널이 그 범위를 넘겨 주지 않음. 부팅은 계속됨. QEMU virt의 정상 실행에서는 나오지 않음 | +| `root: tcb status tests pass` | 태스크가 시작 전인지, 살아 있는지, 끝났는지 알려 주는 호출(`TCB_STATUS`)이 각 상태의 태스크에 대해 올바른 답을 줌. `root: fault isolation tests pass` 뒤에 나옴 | | `root: timeout tests pass` | IPC 타임아웃 자가 테스트가 통과함 | +| `root: untyped split tests pass` | 큰 블록에서 `UNTYPED_SPLIT`으로 잘라낸 8 그래뉼짜리 메모리 예산을 받은 태스크가 거기서 오브젝트를 정확히 8개 얻음. 그 뒤 블록을 회수해 처음부터 다시 사용했고, 거기서 읽은 프레임은 0이었음. `root: timeout tests pass` 뒤에 나옴 | | `root: slice test yield pass`, `root: slice test block pass` | 두 틱 사이에 CPU를 받은 태스크(`YIELD` 또는 앞선 태스크가 기다림)가 처음 만난 틱에 끊기지 않았음. `root: preempt test pass`보다 앞에 나옴 | | `root: preempt test pass` | 양보하지 않는 태스크는 여전히 타이머가 끊음 | | `root: partition refusal pass` | 시간 분할의 두 시스템 콜이 잘못된 요청을 모두 거부함(틀린 케이퍼빌리티, 형식이 틀린 표, 호출자의 도메인이 없는 표, 범위 밖의 도메인, 이미 실행된 태스크, 제어 케이퍼빌리티의 복사) | @@ -220,7 +222,7 @@ $ cargo run -p k0-kernel --features console,terminal,vault-ed25519 `cargo run`은 직렬 포트를 내 터미널에 연결해 QEMU를 시작합니다. 이때 QEMU 자신의 이스케이프 키는 `Ctrl-A`입니다(`Ctrl-A`를 누른 다음 `X`로 QEMU 종료). 따라서 `Ctrl-A`는 K0에 전달되지 않습니다. -자가 테스트가 끝나면 루트 태스크가 볼트를 시작해 부트 시드를 넘기고, 터미널과 똑같이 연결한 적대적 태스크 둘을 돌리고(둘 다 거부되어 폴트로 끝나야 함), 관리자 케이퍼빌리티를 버린 뒤 터미널을 시작합니다. 부트 로그에는 `root: vault seeded`, `root: terminal console filter [...]`, `root: terminal wiring holds`, `k0: task fault` 두 줄, `root: service started`, 그다음 배너가 나옵니다. 입력 경로가 없는 머신에서는 `root: no console input, terminal not started`가 나옵니다. 처음 읽은 뒤에는 주기적인 `k0: tick N` 줄이 멈추고, `k0: tick lines off (console input in use)` 한 줄이 그 사실을 알립니다. 다음 세션에서 모든 명령은 `ok` 또는 `err ` 중 정확히 한 줄로 끝납니다. +자가 테스트가 끝나면 루트 태스크가 볼트를 다시 시작하는 방법을 시험해 보고, 볼트를 시작해 부트 시드를 넘기고, 터미널과 똑같이 연결한 적대적 태스크 둘을 돌리고(둘 다 거부되어 폴트로 끝나야 함), 관리자 케이퍼빌리티를 버린 뒤 터미널을 시작합니다. 부트 로그에는 `root: vault restart test pass`, `root: vault seeded`, `root: terminal console filter [...]`, `root: terminal wiring holds`, `k0: task fault` 두 줄, `root: terminal restart test pass`, `root: service started`, 그다음 배너가 나옵니다. 그 뒤로 터미널과 볼트가 계속 실행되는 동안 루트 태스크는 아무것도 출력하지 않습니다(아래 "터미널이나 볼트가 끝날 때" 참고). 입력 경로가 없는 머신에서는 `root: no console input, terminal not started`가 나옵니다. 처음 읽은 뒤에는 주기적인 `k0: tick N` 줄이 멈추고, `k0: tick lines off (console input in use)` 한 줄이 그 사실을 알립니다. 다음 세션에서 모든 명령은 `ok` 또는 `err ` 중 정확히 한 줄로 끝납니다. ``` K0 operator console, type 'help' @@ -296,12 +298,44 @@ k0> - **하드웨어**: 16550 콘솔에는 입력이 없습니다. SBSA UART 경로, FIFO 오버런, 수신 타임아웃 인터럽트는 QEMU로 실행되지 않고 가짜 UART를 쓰는 호스트 테스트로만 다룹니다. UART 원인 없이 발생하는 인터럽트 선을 끊는 동작도 호스트 테스트로만 다룹니다. 플러드 상황에서 커널이 쓰는 시간을 머신에서 측정하는 테스트는 없습니다. 실제 하드웨어에서는 아무것도 돌려 보지 않았습니다. - **화면**: 입력 중에 커널 줄이 나타나면 화면의 줄은 갈라지지만 버퍼는 온전하며, Enter는 버퍼 전체를 실행합니다. `Console` 출력이 있는 태스크는 여전히 커널이나 루트 태스크 줄처럼 보이는 줄을 출력할 수 있고, 접두어를 인증하는 것은 없습니다. 터미널은 추가로 자기 현재 줄 안을 지울 수 있습니다. - **붙잡힌 바이트**: "프롬프트 전에 버림"은 UART에 도착한 바이트를 말합니다. 바이트를 붙잡아 두는 에뮬레이터나 어댑터는 나중에 전달합니다(QEMU가 그렇습니다). -- **서비스**: 서비스 모드에는 서명 클라이언트가 아직 없습니다. 키는 만들어지고 보이지만 다른 태스크가 사용하지 않습니다. 터미널과 볼트는 죽어도 다시 시작되지 않습니다. 루트 태스크는 신뢰 대상입니다. +- **서비스**: 서비스 모드에는 서명 클라이언트가 아직 없습니다. 키는 만들어지고 보이지만 다른 태스크가 사용하지 않습니다. 터미널과 볼트가 끝나면 루트 태스크가 부팅당 각각 최대 3번 다시 시작하며, 다시 시작한 볼트에는 키가 없습니다(아래 "터미널이나 볼트가 끝날 때" 참고). 루트 태스크는 신뢰 대상입니다. - **부트 로그**: 터미널 출력은 메모리 부트 로그의 사용자 몫을 소모합니다. 그 몫이 차면 이후 태스크 출력은 거기에 기록되지 않습니다. - **볼트**: 이전의 한계는 모두 유지됩니다. 구현은 검증을 받지 않았고, 부채널 분석이 없으며, 키는 승인된 난수 비트 생성기에서 나오지 않고, 영속성도 PQC도 없습니다. 볼트와 터미널의 가용성은 보호되지 않습니다. 콘솔 인터럽트 번호가 틀려도 잃는 것은 입력 경로뿐이며, 부트 로그에 `k0: console input off (...)`가 나옵니다. 이유는 `no console`, `no receive driver for this uart`, `no usable interrupt in the device tree`, `register frame too small`, `console not attached`, `interrupt number out of range`, `interrupt not available`입니다. UART 원인 없이 계속 발생하는 인터럽트 선은 8번 진입한 뒤 `k0: console input off (interrupt N fired without a uart cause)`와 함께 꺼집니다. 입력이 켜지면 부트 로그에 `k0: console input on (pl011 irq 33)`이 나옵니다. 인터럽트 번호는 플랫폼 줄(`k0: platform con=pl011@0x9000000,irq33 ...`)에 들어 있으므로, 이번 변경 이전에 만든 `K0_PIN`은 더 이상 맞지 않아 다시 만들어야 합니다. +### 터미널이나 볼트가 끝날 때 + +터미널 이미지에서 루트 태스크는 터미널과 볼트를 지켜봅니다. 두 번째 틱마다, 곧 2초마다 두 태스크가 아직 살아 있는지 커널에 묻습니다. 정상 세션에서는 루트 태스크의 줄이 나오지 않습니다. 태스크가 예를 들어 폴트로 끝나면, 루트 태스크는 그 태스크를 만든 메모리를 되찾고 같은 자리에 서비스를 다시 시작합니다. 서비스마다 부팅당 최대 3번 다시 시작하고, 그때마다 먼저 더 오래 기다립니다. 적어도 2틱, 그다음 8틱, 그다음 32틱입니다. + +다음 표는 `root: service started` 뒤에 루트 태스크가 출력할 수 있는 줄과 각각의 의미입니다. + +| 줄 | 의미 | +| --- | --- | +| `root: terminal ended, restart 1 of 3 after at least 2 ticks` | 터미널 태스크가 끝났음. 대기 뒤에 돌아옴. 숫자는 `restart 3 of 3 after at least 32 ticks`까지 올라감 | +| `root: terminal started again` | 새 터미널 태스크가 실행됨. 배너와 프롬프트가 다시 나오고, 입력하던 것은 사라짐 | +| `root: vault ended and erased, restart 1 of 3 after at least 2 ticks` | 볼트 태스크가 끝났고 그 메모리를 지웠음. 대기 뒤에 키가 없는 볼트가 돌아옴 | +| `root: vault started again without a key` | 새 볼트 태스크가 실행됨. 시드도 키도 없고 받을 수도 없음. `vault status`는 `state=zeroized`를 보여 줌 | +| `root: terminal ended, no console input, not started again` | 터미널이 끝났고 커널에 콘솔 입력 경로가 없어서, 새 터미널이 읽을 것이 없음 | +| `root: terminal ended, restart budget spent, not started again` | 터미널이 세 번째로 다시 시작한 뒤에 끝났음. 재부팅할 때까지 내려가 있음 | +| `root: vault ended and erased, restart budget spent, not started again` | 볼트가 세 번째로 다시 시작한 뒤에 끝났음. 재부팅할 때까지 내려가 있음 | +| `root: vault stopped and erased, no terminal` | 터미널이 완전히 내려가서 루트 태스크가 볼트를 멈추고 그 메모리를 지웠음 | +| `root: vault ended and erased, no terminal, not started again` | 볼트가 다시 시작을 기다리던 중에 터미널이 완전히 내려갔음 | +| `root: supervision over` | 남은 서비스가 없음. 터미널을 다시 쓰려면 재부팅해야 함 | + +> [!IMPORTANT] +> 다시 시작한 볼트에는 키가 없고, 머신을 다시 부팅할 때까지 키를 만들 수 없습니다. 부트 시드는 첫 볼트에 한 번 넘겼고, 루트 태스크는 사본을 남기지 않습니다. + +`vault-ed25519`에서는 그런 볼트에 `vault keygen ed25519`와 `vault pubkey`가 `err zeroized`로 답합니다. 실행 중인 볼트가 없는 동안에는, 5틱 안에 받는 볼트가 없는 볼트 명령이 `err vault-timeout`으로 답합니다. + +여기서 다루지 않는 것은 다음과 같습니다. + +- **멈춰 있는 태스크**: 루트 태스크는 끝난 태스크만 알아챕니다. 끝나지 않은 채 멈춰 있는 터미널이나 볼트는 살아 있는 것으로 보입니다. +- **루트 태스크 자신**: 신뢰 대상이며, 루트 태스크를 지켜보는 것은 없습니다. 서비스를 실행하는 동안 자기 점검 하나가 실패하면 `root: FAIL ...`을 출력하고, 볼트의 메모리를 지우기를 시도한 뒤(`root: vault erased before exit` 또는 `root: vault not erased`) 종료합니다. +- **테스트**: 세션 중에 실제 터미널이나 실제 볼트를 끝내는 테스트는 없습니다. 대기와 3번이라는 한도는 호스트에서 커널을 대신하는 모형으로 테스트하고, 터미널 이미지는 부팅할 때마다 서비스별로 재시작 한 번을 대기 없이 시험합니다(`root: vault restart test pass`, `root: terminal restart test pass`). + +설계는 [design/kr/terminal_KR.md](design/kr/terminal_KR.md#감독)에 있습니다. + ## UEFI로 부팅 UEFI는 많은 컴퓨터에서 펌웨어가 프로그램을 시작하는 표준 방식입니다. 펌웨어가 디스크에서 확장자가 `.efi`인 프로그램 파일을 읽어 실행하고, 그 프로그램에 기계의 구성을 알려 줍니다. 로더는 기계를 준비한 다음 다른 프로그램을 시작하는 일 하나만 하는 작은 프로그램입니다. K0에는 자체 UEFI 로더(`crates/k0-efi`와 `loader/`)가 있습니다. 로더가 커널을 안에 품고 있으므로, 펌웨어에는 `.efi` 파일 하나만 있으면 됩니다. 커널은 바뀌지 않으며 UEFI 없이 부팅할 때와 똑같이 시작합니다. 다음 그림은 UEFI 부팅의 경로를 보여 줍니다. @@ -413,7 +447,7 @@ $ tools/qemu-boot-test.sh # QEMU에서 부팅하 $ tools/boot-matrix.sh # 지원하는 구성을 전부 부팅(16 KiB 이미지, 고정 이미지, UEFI 로더 이미지도 빌드함) ``` -- `tools/host-test.sh`는 호스트 테스트 415개를 실행합니다(그 밖의 호스트에서는 327개). 커널의 부분 하나하나를 내 컴퓨터에서 일반 프로그램처럼 돌리는 작은 테스트(단위 테스트)입니다. **퍼징**도 합니다. 디바이스 트리 파서와 UEFI 로더의 계획 코드에 무작위로 망가뜨린 입력을 넣어 충돌을 찾는 방법입니다. 415개는 `k0-abi` 15개, `k0-cap` 54개, `k0-boot` 85개, `k0-efi` 33개, `k0-conin` 19개, `k0-slice` 9개(틱이 실행 중인 태스크를 끊을지 정하는 규칙을 스케줄러 모델로 검사), `k0-part` 36개(시간 분할 표가 있을 때의 스케줄러 판정과 틱 시각의 산술을 검사하고, Lean 모델의 기록된 결과와도 비교), `k0-vault` 31개(Ed25519를 포함하면 20개, 없으면 11개), `k0-term` 45개(`vault` feature를 포함하면 24개, 없으면 21개), `k0-mm` 44개씩 두 페이지 크기분입니다. 메모리 관리 테스트는 ARM 명령을 사용하므로 ARM 컴퓨터(Apple Silicon Mac이나 Linux arm64)에서만 돌고, 그 밖의 호스트의 개수는 그 88개를 뺀 것입니다. +- `tools/host-test.sh`는 호스트 테스트 457개를 실행합니다(그 밖의 호스트에서는 369개). 커널의 부분 하나하나를 내 컴퓨터에서 일반 프로그램처럼 돌리는 작은 테스트(단위 테스트)입니다. **퍼징**도 합니다. 디바이스 트리 파서와 UEFI 로더의 계획 코드에 무작위로 망가뜨린 입력을 넣어 충돌을 찾는 방법입니다. 457개는 `k0-abi` 16개, `k0-cap` 71개(그 가운데 17개는 untyped 메모리 분할에 관한 것), `k0-boot` 85개, `k0-efi` 33개, `k0-conin` 19개, `k0-slice` 9개(틱이 실행 중인 태스크를 끊을지 정하는 규칙을 스케줄러 모델로 검사), `k0-part` 36개(시간 분할 표가 있을 때의 스케줄러 판정과 틱 시각의 산술을 검사하고, Lean 모델의 기록된 결과와도 비교), `k0-sup` 20개(루트 태스크가 터미널과 볼트를 다시 시작하는 규칙을 커널을 대신하는 모형으로 검사), `k0-vault` 35개(Ed25519를 포함하면 22개, 없으면 13개), `k0-term` 45개(`vault` feature를 포함하면 24개, 없으면 21개), `k0-mm` 44개씩 두 페이지 크기분입니다. 메모리 관리 테스트는 ARM 명령을 사용하므로 ARM 컴퓨터(Apple Silicon Mac이나 Linux arm64)에서만 돌고, 그 밖의 호스트의 개수는 그 88개를 뺀 것입니다. - `tools/qemu-boot-test.sh`는 커널을 부팅하고, 로그를 정해진 순서대로 한 줄씩 확인합니다. 에러 줄이 하나라도 나오면 실패하고, 일부러 일으킨 폴트 줄의 개수를 정확히 맞춘 뒤 QEMU를 끕니다. 루트 태스크의 타임아웃 테스트는 실제 타이머 틱을 기다리므로, 부팅 한 번이 그 테스트가 생기기 전보다 약 4초 더 걸립니다. 시간 조각 테스트는 두 번 실행해 합계 약 4초가 걸리며, 이를 대신한 이전 선점 테스트는 약 1초가 걸렸습니다. 시간 분할 테스트는 9틱짜리 표를 한 바퀴 돌리므로 약 15초를 더하고, 그래서 부팅 테스트 한 번은 이제 약 25초가 걸립니다. 판정 직전에는 `boot-test: partition window retries: N`도 출력합니다. 호스트가 QEMU를 멈춰 세워서 창 테스트를 다시 실행해야 했던 횟수입니다. 스크립트는 이 수로 판정하지 않습니다. `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에서 82행, CI에서 71행입니다. 행 이름을 인자로 주면 그 행만 돌립니다. CI가 이것을 실행합니다. 부팅 행의 창 테스트가 재시도를 했으면 행렬은 그 행을 한 번 더 돌리고, 두 번째 실행도 재시도를 했으면 그 행을 실패로 처리합니다(`matrix: FAIL (the window test needed its retry in two runs)`). @@ -459,7 +493,7 @@ Apple Silicon Mac에서는 `K0_MATRIX_HVF=1 tools/boot-matrix.sh`로 QEMU의 HVF | `term-uefi`, `term-uefi-acpi` | UEFI 로더를 거치는 터미널 이미지(디바이스 트리 경로와 ACPI 경로) | | `hvf-term` | HVF에서의 터미널 이미지(Mac 전용) | -`tools/term-test.py <이미지>`는 QEMU의 직렬 포트를 파이프에 연결해 이미지를 부팅하고 정해진 세션을 실행합니다. 모든 명령과 오류, 지우기와 취소, CR LF, ESC 시퀀스, 너무 긴 줄, 키 생성, 공개 키 형식, zeroize, 줄 끝 없는 200 kB, 연속 2000줄, 직렬 브레이크, 그리고 QEMU 8.0 이상에서는 브레이크 2000번의 폭주를 다룹니다. `tools/qemu-boot-test.sh`는 이미지가 보여야 할 것을 알려 주는 `K0_BOOT_INPUT=on|off`와 `K0_BOOT_SERVICE=vault|plain|none`, 그리고 판정만 하는 모드 `K0_BOOT_JUDGE`도 이해합니다. 터미널 이미지는 터미널 없는 같은 이미지보다 `k0: task fault` 줄이 두 개 더 나오므로(볼트 없이 8개, 볼트와 함께 10개) `K0_BOOT_FAULTS`를 사용하세요. +`tools/term-test.py <이미지>`는 QEMU의 직렬 포트를 파이프에 연결해 이미지를 부팅하고 정해진 세션을 실행합니다. 모든 명령과 오류, 지우기와 취소, CR LF, ESC 시퀀스, 너무 긴 줄, 키 생성, 공개 키 형식, zeroize, 줄 끝 없는 200 kB, 연속 2000줄, 직렬 브레이크, 그리고 QEMU 8.0 이상에서는 브레이크 2000번의 폭주를 다룹니다. `tools/qemu-boot-test.sh`는 이미지가 보여야 할 것을 알려 주는 `K0_BOOT_INPUT=on|off`와 `K0_BOOT_SERVICE=vault|plain|none`, 그리고 판정만 하는 모드 `K0_BOOT_JUDGE`도 이해합니다. 터미널 이미지는 터미널 없는 같은 이미지보다 `k0: task fault` 줄이 두 개 더 나오므로(볼트 없이 8개, 볼트와 함께 10개) `K0_BOOT_FAULTS`를 사용하세요. `K0_BOOT_SERVICE=vault`나 `plain`이면 부팅 테스트는 `root: service started` 앞에 `root: terminal restart test pass`도 기대하고, `vault`이면 시드에 관한 줄 앞에 `root: vault restart test pass`도 기대합니다. `tools/term-test.py`는 프롬프트 뒤의 출력에 `root: `가 나타나면 세션을 실패로 처리합니다. 루트 태스크는 터미널이나 볼트가 끝났을 때만 거기에 출력하기 때문입니다. ### 콘솔 없는 이미지 시험 @@ -542,5 +576,10 @@ $ lake exe vectors --check ../../crates/k0-part/src/model_vectors.txt | 화면에 펌웨어 메시지나 펌웨어 메뉴만 나옴 | 펌웨어가 로더를 시작하지 못했거나, 로더가 거부해서 펌웨어가 다음으로 넘어간 것입니다. `k0-loader:` 줄이 있는지 보세요. 없다면 `.efi` 파일이 있는지, `K0_QEMU_ESP`를 사용했다면 드라이브가 보이는지 확인하세요 | | 터미널에 `k0> ` 프롬프트가 나오지 않음 | 이미지를 `terminal`(과 `console-input`) 없이 빌드했거나, 로그에 `k0: console input off (...)` 또는 `root: no console input, terminal not started`가 있습니다. `--features console,terminal,vault-ed25519`로 빌드하고 부트 로그에서 이유를 읽으세요 | | 입력해도 반응이 없거나 `Ctrl-A`가 전달되지 않음 | `cargo run`에서는 QEMU가 `Ctrl-A`를 자기 몫으로 씁니다. 16550 콘솔에는 입력이 전혀 없습니다 | +| `root: terminal ended, restart ...`가 나오고 나중에 배너가 다시 나옴 | 터미널 태스크가 끝나서 루트 태스크가 새 터미널을 시작했습니다. 입력하던 것은 사라졌습니다. 그 앞에 `k0: task fault` 줄이 있는지 보면 터미널이 폴트로 끝났는지 알 수 있습니다. "터미널이나 볼트가 끝날 때"를 참고하세요 | +| `root: vault ended and erased, ...`나 `root: vault started again without a key`가 나오거나, 키를 지운 적이 없는데 `vault status`가 `state=zeroized`를 보여 줌 | 볼트 태스크가 끝났습니다. 그 메모리는 지워졌고, 그 자리에 시작한 볼트에는 키가 없습니다. 키를 다시 얻으려면 재부팅하세요 | +| 줄이 `not started again`으로 끝나거나 `root: supervision over`가 나옴 | 서비스가 재시작 3번을 다 썼거나, 콘솔 입력 경로가 없는 머신에서 터미널이 끝났습니다. 그 서비스는 재부팅할 때까지 내려가 있습니다 | +| `root: vault erased before exit` 또는 `root: vault not erased`가 나옴 | 서비스를 실행하는 동안 루트 태스크의 점검이 실패했습니다. 그 앞의 `root: FAIL ...` 줄에 단계 이름이 있습니다. 루트 태스크는 종료했고 더 이상 서비스를 지켜보지 않습니다 | +| `term-test: FAIL kernel line during the session`에 `root: ` 줄이 보임 | 스크립트 세션 중에 터미널이나 볼트가 끝나서 루트 태스크가 그것을 알렸습니다. 정상 세션에서는 일어나지 않아야 합니다. 스크립트가 알려 주는 로그 파일을 읽으세요 | | 터미널 이미지에서 `boot-test`가 `k0: task fault` 줄 수 때문에 실패 | 그 이미지는 터미널 없는 이미지보다 2개 더 출력합니다(8개 또는 10개). `K0_BOOT_FAULTS`를 사용하세요 | | 이전에 만든 `K0_PIN`이 더 이상 맞지 않음 | 플랫폼 줄에 이제 콘솔 인터럽트(`irq33`)가 들어 있습니다. 핀을 다시 만드세요 | diff --git a/assets/supervision.svg b/assets/supervision.svg new file mode 100644 index 0000000..a1042fe --- /dev/null +++ b/assets/supervision.svg @@ -0,0 +1,81 @@ + + Supervision of the terminal and the vault + The root task asks the kernel with TCB_STATUS at every second tick whether the terminal task and the vault task ended. Each service has a seat: a slab of 16 granules and a fixed range of root CNode slots. When a task has ended, the root task revokes the slab, erases the slab if it is the vault, waits at least 2, 8 and 32 ticks before restart 1, 2 and 3, and builds the service again in the same slab and the same slots. A vault that is built again has no seed and no key. After 3 restarts per boot a service stays down, and when the terminal stays down the vault is stopped and erased. + + + + + + + + + + Root task (trusted) + polls at every second tick + waits only on its own endpoint + nothing supervises it + + + TCB_STATUS + one call per service + + + Kernel (EL1) + answers ALIVE or ENDED + gives no reason + tells nobody by itself + + + + + Terminal seat + slab of 16 granules, fixed slots + + Vault seat + slab of 16 granules, fixed slots + + + a task is ENDED + + + 1. Retire + CAP_REVOKE on the slab + removes the task, its CNode + and its address space + + + + 2. Erase + only for the vault + RETYPE all 16 granules + as frames, then revoke + + + + 3. Wait + at least 2, 8 and 32 ticks + before restart 1, 2 and 3 + + + + 4. Rebuild + same slab and same slots + a new vault has no key + + + After 3 restarts per boot a service stays down until the next boot. + When the terminal stays down, the vault is stopped and erased as well. + diff --git a/assets/supervision_KR.svg b/assets/supervision_KR.svg new file mode 100644 index 0000000..431372d --- /dev/null +++ b/assets/supervision_KR.svg @@ -0,0 +1,81 @@ + + 터미널과 볼트의 감독 + 루트 태스크는 두 번째 틱마다 TCB_STATUS로 터미널 태스크와 볼트 태스크가 끝났는지 커널에 묻습니다. 서비스마다 자리가 있습니다. 자리는 16 그래뉼짜리 슬랩과 루트 CNode의 고정된 슬롯 구간입니다. 태스크가 끝났으면 루트 태스크는 슬랩을 회수하고, 볼트라면 슬랩을 지우고, 재시작 1, 2, 3 전에 적어도 2, 8, 32틱을 기다린 뒤, 같은 슬랩과 같은 슬롯에 서비스를 다시 만듭니다. 다시 만든 볼트에는 시드도 키도 없습니다. 부팅당 3번 다시 시작한 뒤에는 서비스가 내려간 채로 남고, 터미널이 내려간 채로 남으면 볼트도 멈추고 지웁니다. + + + + + + + + + + 루트 태스크(신뢰 대상) + 두 번째 틱마다 폴 + 자기 엔드포인트에서만 대기 + 루트 태스크를 감독하는 것은 없음 + + + TCB_STATUS + 서비스마다 호출 한 번 + + + 커널(EL1) + ALIVE 또는 ENDED로 답함 + 이유는 알리지 않음 + 스스로는 알리지 않음 + + + + + 터미널의 자리 + 16 그래뉼짜리 슬랩, 고정된 슬롯 + + 볼트의 자리 + 16 그래뉼짜리 슬랩, 고정된 슬롯 + + + 태스크가 ENDED + + + 1. 걷어 내기 + 슬랩에 CAP_REVOKE + 태스크, 그 CNode, + 주소 공간이 사라짐 + + + + 2. 지우기 + 볼트만 해당 + 16 그래뉼 전부를 프레임으로 + RETYPE한 뒤 회수 + + + + 3. 기다리기 + 재시작 1, 2, 3 전에 + 적어도 2, 8, 32틱 + + + + 4. 다시 만들기 + 같은 슬랩과 같은 슬롯 + 새 볼트에는 키가 없음 + + + 부팅당 3번 다시 시작한 뒤에는 다음 부팅까지 서비스가 내려간 채로 남습니다. + 터미널이 내려간 채로 남으면 볼트도 멈추고 지웁니다. + diff --git a/ci/threat_model.md b/ci/threat_model.md index cbedf2e..f6644ad 100644 --- a/ci/threat_model.md +++ b/ci/threat_model.md @@ -9,6 +9,8 @@ Read `SECURITY.md` at the repository root first. It describes the isolation mode 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. + + The two newest calls are `UNTYPED_SPLIT` (19, `sys_untyped_split`, which calls `k0_cap::split`) and `TCB_STATUS` (20, `sys_tcb_status`). Both take their arguments in registers only and are in every image. `UNTYPED_SPLIT` takes two slots and a granule count: the count is attacker controlled, it is multiplied by the granule and added to the watermark of the untyped, and a count of 0 is refused with `BAD_SIZE` before the slots are looked at. The call writes two slots and no memory. `TCB_STATUS` takes one slot, reads the state field of the TCB it names through the kernel alias and writes nothing. Its successful result is 0, 1 or 2, so it is the only call that returns something other than 0 in `x0` on success. 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, the time partition table and the expiry of IPC timeouts. The tick number is computed from the counter (`k0_part::clock::fire`, called from `timer_tick` in `crates/k0-arch/src/irq.rs`), so a late handler skips numbers. Every scheduling decision is in `crates/k0-part` (type `Core`: which domain runs at a tick, and, with the tick rule of `crates/k0-slice`, whether the tick cuts the running task). `crates/k0-sched` holds the queues around it and is called through `on_tick` from EL0 and `poll` from the wait loop. `k0_ipc::expire_timeouts` runs for the running domain only, at every tick of its window and from the wait loop. Before a tick that changes the domain the timer is armed 25 ms early (`guard_next`), and every return from an exception to EL0 ends in `k0_leave` in `kernel/src/syscall.rs`, which checks the task and holds until the tick instant (`hold_until_due`). @@ -18,7 +20,9 @@ Trust boundaries, from least to most trusted: 6. **The UEFI loader** (`loader/`, `crates/k0-efi`) sits between the firmware and the kernel, and it is in scope. Its inputs come from firmware and are treated as wrong or hostile data: the UEFI memory map, the firmware device tree or, without one, the ACPI static tables (RSDP, XSDT, MADT, GTDT, SPCR) from the configuration table, the random number protocol and the embedded kernel image. It decides which memory the kernel sees as RAM, so a mistake there hands firmware memory to user space without any kernel bug. Entry path: `loader/src/load.rs` (flow) -> `crates/k0-efi/src/prepare.rs` (plan, rewrite, self-check with the kernel's own parser, discovery, `Platform::validate` and `boot_window`) -> `loader/src/handoff.rs` (cache flush, MMU off, jump). The pure logic is in `memmap.rs`, `fdtw.rs`, `verify.rs` and `image.rs` of `k0-efi`, none of it `unsafe`. The loader does not verify a signature: its SHA-256 over the embedded kernel is a corruption check, and authenticity is the firmware's Secure Boot job. 7. **The vault task and its clients** (optional, features `vault` and `vault-ed25519` of `k0-kernel`). The vault holds one Ed25519 key in its own address space. Clients send requests over one endpoint with a badge that the kernel delivers; the badge selects the role (admin, operator, signer, reader) in a policy fixed at build time. The operator is the terminal of boundary 8. Everything in a request (operation, algorithm, length, message, nonce) is attacker controlled, and the vault reads the body once into a private buffer. The root task builds the vault and is trusted, so a root task that reads the vault is not a finding. Entry path: `userspace/k0-vault` (`server`, `proto`, `provider`) and the wiring and self-test in `userspace/root-task/src/oracle.rs`. The Ed25519 code is the vendored crate `ed25519-dalek` 2.2.0, which has no validation of any kind. -8. **The serial line and the operator terminal** (optional, features `console-input` and `terminal` of `k0-kernel`). Every byte that arrives on the console UART is attacker controlled, and so is its timing. The kernel's receive path runs at EL1 in interrupt context: it puts bytes into a ring of 256 bytes and never interprets them, and the console interrupt is the second interrupt source after the timer. `CONSOLE_READ` hands one byte at a time to the one task that holds a `Console` capability with the read right (R). The terminal task (`userspace/k0-term`) parses lines in its own address space and, when the vault is built in, acts as the vault's operator: it can ask for `STATUS`, `PUBLIC_KEY`, `KEYGEN` and `ZEROIZE`, nothing else. There is no authentication on the serial line, so whoever reaches it is the operator, and erasing the key is a denial of service by design. Entry path: `crates/k0-arch/src/conin.rs` and `crates/k0-conin` (receive logic), `crates/k0-ipc/src/console.rs` and `kernel/src/syscall.rs` (`CONSOLE_READ`, the rights of `Console`), `userspace/k0-term` (`lib.rs`, `wire.rs`) and its wiring in `userspace/root-task/src/oracle.rs`. The interrupt number comes from the device tree or the ACPI SPCR table, which are inputs of boundary 4 and 6. +8. **The serial line and the operator terminal** (optional, features `console-input` and `terminal` of `k0-kernel`). Every byte that arrives on the console UART is attacker controlled, and so is its timing. The kernel's receive path runs at EL1 in interrupt context: it puts bytes into a ring of 256 bytes and never interprets them, and the console interrupt is the second interrupt source after the timer. `CONSOLE_READ` hands one byte at a time to the one task that holds a `Console` capability with the read right (R). The terminal task (`userspace/k0-term`) parses lines in its own address space and, when the vault is built in, acts as the vault's operator: it can ask for `STATUS`, `PUBLIC_KEY`, `KEYGEN` and `ZEROIZE`, nothing else. There is no authentication on the serial line, so whoever reaches it is the operator, and erasing the key is a denial of service by design. Entry path: `crates/k0-arch/src/conin.rs` and `crates/k0-conin` (receive logic), `crates/k0-ipc/src/console.rs` and `kernel/src/syscall.rs` (`CONSOLE_READ`, the rights of `Console`), `userspace/k0-term` (`lib.rs`, `wire.rs`) and its wiring in `userspace/root-task/src/service.rs`. The interrupt number comes from the device tree or the ACPI SPCR table, which are inputs of boundary 4 and 6. + + In a terminal image the root task supervises the terminal and the vault. Every second tick it asks `TCB_STATUS` for both tasks. When one has ended, it revokes the child `Untyped` the task was built from and builds the task again, at most 3 times per service per boot (`Supervisor::poll` in `userspace/k0-sup`, and `retire_seat`, `build_terminal` and `build_vault` in `userspace/root-task/src/service.rs`). The memory of an ended vault is erased by retyping all of it, and a vault that is started again takes no seed and makes no key (`Vault::retired`). So whatever makes the terminal task end, a fault included, makes the root task run this path, and when the terminal ends once more after its third restart it stays down and the vault is stopped and erased. Out of the kernel's control and therefore trusted: the rest of the boot chain (firmware, any other boot loader, the hypervisor), the integrity of the kernel image itself, and the hardware. Under UEFI the firmware is trusted to run honestly, but the loader must still not trust what it describes. @@ -55,7 +59,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: partition refusal pass`, `root: partition window 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`, `root: partition sealed` and `root: sched tests pass`. The partition window test lets a table of 9 ticks run one round, so a boot takes about 15 seconds longer than it did, and the periodic `k0: tick N` lines pause while a table is set. A line `root: partition window retry` means that the host stalled QEMU for more than a second and the window test ran once more; that alone is not a finding. 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`. For the time partitions the wrappers are `part_set_table` and `part_set_domain`, and `userspace/root-task/src/partition.rs` is the existing test. The root task deletes `PartCtl` in `partition::seal()`, so a reproducer that needs a table must run before that call. EL0 has no clock, so a reproducer has to show its point by the order of events, as that test does. 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-slice`, `k0-part`, `k0-vault` and `k0-term` on any host and those of `k0-mm` on AArch64 hosts. `k0-part` runs the real scheduling core on a model of the kernel, and one of its tests (`core_gives_the_lines_of_the_lean_model_on_every_recorded_script`) compares it with 1600 recorded results of a Lean model. The Lean files themselves (`proofs/lean`) are not in this image, and they are proofs about a model, not about the Rust code. `k0-sched`, `k0-ipc` and the kernel binary have no host tests. `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-part`, `k0-sup`, `k0-vault` and `k0-term` on any host and those of `k0-mm` on AArch64 hosts. `k0-sup` runs the policy that supervises the terminal and the vault on a mock host. `k0-part` runs the real scheduling core on a model of the kernel, and one of its tests (`core_gives_the_lines_of_the_lean_model_on_every_recorded_script`) compares it with 1600 recorded results of a Lean model. The Lean files themselves (`proofs/lean`) are not in this image, and they are proofs about a model, not about the Rust code. `k0-sched`, `k0-ipc` and the kernel binary have no host tests. `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. @@ -86,7 +90,7 @@ 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 inside a domain with a tick of one second, no priority or CPU budget, so a task with `Untyped` memory can dilute the share of everybody in its domain by creating tasks, which stays known; under a time partition table a timeout can also fire late, when the waiter's domain next runs); 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; the lines the kernel prints when a task ends share 4 KiB of the boot log and no longer reach its kernel part, but a task that can create tasks can still push such lines of other tasks out of the 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 inside a domain with a tick of one second, no priority or CPU budget, so a task with `Untyped` memory can dilute the share of everybody in its domain by creating tasks, which stays known; under a time partition table a timeout can also fire late, when the waiter's domain next runs); 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; a child `Untyped` made with `UNTYPED_SPLIT` bounds the memory and the number of objects of the task that holds it, not the time of such a call; `k0_arch::fatal`, a kernel panic and an SError from EL0 stop the machine; the lines the kernel prints when a task ends share 4 KiB of the boot log and no longer reach its kernel part, but a task that can create tasks can still push such lines of other tasks out of the 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 `Core` in `crates/k0-part`), so with one domain 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. A Lean theorem states the bound for a model of one domain, which is not a proof about the Rust code, 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 between tasks of one domain (a task changes when, and for how long, another task of its domain runs by choosing when to yield or block, and this has not been analysed), and every image built today has one domain; there is no latency promise (a task that becomes ready can wait up to one tick longer than before); under a time partition table the end of a window takes the CPU whatever the rule says; the measurements ran in QEMU only, with an attacker whose yield point was set for it. The kernel no longer passes an entry kind to the scheduler, so the three connections that only a host model covered before (the tick's own switch, the wait loop's report of a tick, the entry kind at the hand-off to the root task) are now decided inside `Core` and covered by the host tests of `k0-part`. A report that one of them is wrong is still welcome. - Fixed time partitions, all in `SECURITY.md` under "Fixed time partitions". The claim is that they close the channel between domains that goes through the scheduler, and nothing more. No image uses more than one domain yet: the root task deletes `PartCtl` at the end of its self-tests, so every image built today runs sealed with one domain. Known limits, not new findings: a kernel path longer than the guard (25 ms) that is in flight when the guard starts delays the start of the next window (`CAP_REVOKE`, large deletes); caches and branch predictors are not flushed at a change of domain (the TLB is); the time of console input interrupts and of the UART work in the tick handler lands in whichever domain runs; the UART, the boot log, the single console waiter slot (`BUSY`) and the kernel memory pools are shared between domains; a stall longer than a tick skips windows, because tick numbers follow the counter and skipped ticks are not replayed; an endpoint shared across domains is a channel by design, and so is every other capability operation on an object shared with another domain (deleting or revoking an endpoint its tasks wait on, the end of a task that holds its reply, `TCB_RESUME`, deleting its TCB); a task woken by console input inside the guard of an empty incoming window starts at the tick instant and still skips its first tick rotation, inside its own domain; no test sees the guard, the hold or the TLB flush, because EL0 cannot time anything, and the console rule under a table has no test; the Lean proofs are about a model; nothing ran on real hardware. A table must contain the caller's domain, a task in a domain that no table names never runs, and a timeout fires late when the waiter's domain is not running: all three are by design. The system call ABI changed with this (`bootinfo::VERSION` 5, first untyped slot 6), so a root task built for an earlier `main` does not run. - 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. @@ -95,7 +99,7 @@ These are known, tracked in `SECURITY.md`, and are not new findings: - 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 for bytes and by 256 per tick for characters with a line error), 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. +- 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 for bytes and by 256 per tick for characters with a line error), 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 root task starts the terminal and the vault again at most 3 times per boot, by polling, and it is trusted and not supervised itself; a service that hangs without ending is not noticed; a vault that is started again has no key; no committed test makes the real terminal or the real vault end during service; 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-abi/src/lib.rs b/crates/k0-abi/src/lib.rs index 4cf30d4..f7eb3ed 100644 --- a/crates/k0-abi/src/lib.rs +++ b/crates/k0-abi/src/lib.rs @@ -49,7 +49,8 @@ pub mod syscall { /// x0 = untyped 슬롯, x1 = 오브젝트 타입([super::obj]), x2 = 새 /// 케이퍼빌리티를 받을 빈 슬롯. 목적지를 호출자가 지정하므로 커널은 /// 빈 슬롯을 찾지 않습니다(상수 시간). untyped에서 파생된 케이퍼빌리티가 - /// 하나도 남아 있지 않으면 그 메모리를 처음부터 재사용합니다. 성공 시 + /// 하나도 남아 있지 않으면 그 메모리를 처음부터 재사용합니다. 잘라낸 + /// 자식 untyped([UNTYPED_SPLIT])도 파생된 케이퍼빌리티로 셉니다. 성공 시 /// x0 = 0, 실패 시 음수 에러([super::err]) pub const RETYPE: u64 = 3; /// 케이퍼빌리티를 AddrSpace 케이퍼빌리티가 가리키는 주소 공간에 매핑 @@ -120,12 +121,18 @@ pub mod syscall { /// 케이퍼빌리티를 그 자손과 함께 삭제 /// /// x0 = 슬롯. 오브젝트의 원본 케이퍼빌리티(재분류가 만든 것)를 삭제하면 - /// 그 오브젝트가 종료됩니다. 성공 시 x0 = 0 + /// 그 오브젝트가 종료됩니다. 자식 untyped를 삭제해도 그 구간은 부모에게 + /// 곧바로 돌아가지 않습니다. 부모에서 파생된 것이 하나도 남지 않아야 + /// 부모가 처음부터 다시 자릅니다. 성공 시 x0 = 0 pub const CAP_DELETE: u64 = 14; /// 케이퍼빌리티에서 파생된 것을 전부 회수(자신은 남김) /// - /// x0 = 슬롯. untyped를 회수하면 거기서 잘라낸 오브젝트가 전부 종료되고 - /// 메모리를 다시 재분류할 수 있습니다. 성공 시 x0 = 0 + /// x0 = 슬롯. untyped를 회수하면 거기서 잘라낸 오브젝트와 자식 untyped가 + /// 전부 사라지고 메모리를 다시 재분류할 수 있습니다. 자식 untyped를 + /// 회수하면 메모리는 부모가 아니라 그 자식에게 돌아갑니다. 회수하는 + /// 슬롯 자신이 이 호출로 종료되는 CNode나 TCB 안에 있으면 그 슬롯도 함께 + /// 사라집니다. 메모리는 지워지지 않고, 다시 재분류될 때 지워집니다. 성공 + /// 시 x0 = 0 pub const CAP_REVOKE: u64 = 15; /// 콘솔 입력에서 바이트 하나를 읽음(커널을 `console-input`으로 빌드한 /// 이미지에만 있음) @@ -156,6 +163,37 @@ pub mod syscall { /// 부른 태스크의 도메인을 물려받으므로, 다른 도메인에 두려면 이 호출이 /// 필요합니다. 도메인이 표에 있는지는 보지 않습니다. 성공 시 x0 = 0 pub const PART_SET_DOMAIN: u64 = 18; + /// untyped에서 더 작은 자식 untyped를 잘라냄 + /// + /// x0 = untyped 슬롯, x1 = 그래뉼 수(1 이상), x2 = 자식을 받을 빈 슬롯. + /// 자식은 부모의 워터마크를 그래뉼 경계로 올린 자리에서 시작하고 부모의 + /// 자손이 됩니다. 메모리는 건드리지 않습니다(소거는 RETYPE가 함). 부모에서 + /// 파생된 케이퍼빌리티가 하나도 남아 있지 않으면 RETYPE처럼 처음부터 다시 + /// 자릅니다. 자식은 복사할 수 없고 CAP_MOVE로 넘길 수 있으며 다시 자를 수 + /// 있습니다. 자식에서 나올 수 있는 오브젝트는 그 그래뉼 수만큼입니다. + /// 그래뉼 수가 0이면 x0 = BAD_SIZE이고 이 검사는 슬롯보다 먼저입니다. + /// 남은 자리에 들어가지 않으면 EXHAUSTED. 성공 시 x0 = 0 + pub const UNTYPED_SPLIT: u64 = 19; + /// 태스크가 시작됐는지, 끝났는지를 물음 + /// + /// x0 = TCB 슬롯. 아무것도 바꾸지 않습니다. 성공 시 x0 = 그 태스크의 + /// 상태([super::tcb_status], 0 이상), 실패 시 음수 에러입니다. 성공값이 + /// 0이 아닐 수 있는 호출은 이것뿐입니다. 끝난 까닭(종료 코드, 폴트, 회수)과 + /// 살아 있는 태스크가 무엇을 하고 있는지는 알려 주지 않습니다. 끝난 + /// 태스크는 다시 시작되지 않으므로 [super::tcb_status::ENDED]는 그 + /// 케이퍼빌리티가 있는 동안 바뀌지 않습니다. 물을 수 있는 것은 그 TCB의 + /// 케이퍼빌리티를 쥔 태스크뿐이고, 커널이 먼저 알려 주는 일은 없습니다 + pub const TCB_STATUS: u64 = 20; +} + +/// TCB_STATUS가 x0으로 돌려주는 상태 모듈입니다. +pub mod tcb_status { + /// 아직 시작되지 않음(구성 전이거나, 구성만 되고 재개되지 않음) + pub const NOT_STARTED: i64 = 0; + /// 시작됐고 끝나지 않음(준비, 실행, 대기를 구별하지 않음) + pub const ALIVE: i64 = 1; + /// 끝났음. 한 번도 실행되지 않은 채 끝난 것도 포함함 + pub const ENDED: i64 = 2; } /// CONSOLE_READ의 플래그(x1)와 결과(x2) 모듈입니다. @@ -303,6 +341,8 @@ pub mod err { pub const BAD_TABLE: i64 = -25; /// 도메인 번호가 범위 밖임 pub const BAD_DOMAIN: i64 = -26; + /// 크기 인자가 0임 + pub const BAD_SIZE: i64 = -27; } /// 커널이 루트 태스크에 RO로 매핑해 주는 bootinfo 페이지 모듈입니다. diff --git a/crates/k0-abi/src/tests.rs b/crates/k0-abi/src/tests.rs index 6085374..2ee427d 100644 --- a/crates/k0-abi/src/tests.rs +++ b/crates/k0-abi/src/tests.rs @@ -32,6 +32,8 @@ fn syscall_numbers_are_unique_and_dense() { syscall::CONSOLE_READ, syscall::PART_SET_TABLE, syscall::PART_SET_DOMAIN, + syscall::UNTYPED_SPLIT, + syscall::TCB_STATUS, ]; assert_unique(&nrs.map(i128::from)); for (i, nr) in nrs.iter().enumerate() { @@ -68,6 +70,7 @@ fn error_codes_are_unique_and_negative() { err::NO_DEVICE, err::BAD_TABLE, err::BAD_DOMAIN, + err::BAD_SIZE, ]; assert_unique(&errs.map(i128::from)); for e in errs { @@ -76,6 +79,17 @@ fn error_codes_are_unique_and_negative() { } } +#[test] +fn task_status_values_are_distinct_and_never_look_like_an_error() { + let values = [tcb_status::NOT_STARTED, tcb_status::ALIVE, tcb_status::ENDED]; + assert_unique(&values.map(i128::from)); + // 성공값은 0 이상이고 에러는 음수라 한 레지스터로 구별됨 + for v in values { + assert!(v >= 0, "status {v} would read as an error"); + } + assert_eq!(values, [0, 1, 2]); +} + #[test] fn object_types_exclude_zero() { let kinds = [ diff --git a/crates/k0-boot/build.rs b/crates/k0-boot/build.rs index 5c9a0a3..7e43c5b 100644 --- a/crates/k0-boot/build.rs +++ b/crates/k0-boot/build.rs @@ -257,6 +257,8 @@ fn main() { "userspace/k0-vault/Cargo.toml", "userspace/k0-term/src", "userspace/k0-term/Cargo.toml", + "userspace/k0-sup/src", + "userspace/k0-sup/Cargo.toml", "Cargo.lock", "userspace/root-task/Cargo.toml", "userspace/root-task/build.rs", diff --git a/crates/k0-cap/src/lib.rs b/crates/k0-cap/src/lib.rs index 197a2ec..1c1d233 100644 --- a/crates/k0-cap/src/lib.rs +++ b/crates/k0-cap/src/lib.rs @@ -11,7 +11,9 @@ //! 자기 CNode를 가지므로, 슬롯 번호는 호출한 태스크의 CNode 안에서만 의미를 //! 갖습니다. 슬롯들은 파생 리스트(전위 순서의 이중 연결 리스트 + 깊이)로 //! 엮입니다. 복사본은 원본의 자식이고, 재분류로 생긴 케이퍼빌리티는 그 -//! untyped의 자식입니다. 삭제와 회수는 자손을 남기지 않으므로 자식이 부모보다 +//! untyped의 자식입니다. untyped에서 잘라낸 더 작은 untyped(분할)도 그 +//! untyped의 자식이라, 부모를 회수하면 그 아래에서 만든 것과 함께 사라집니다. +//! 삭제와 회수는 자손을 남기지 않으므로 자식이 부모보다 //! 오래 살 수 없고, 오브젝트의 원본(ORIGINAL) 케이퍼빌리티가 사라진 채로 //! 복사본만 남는 일이 없습니다. 원본이 지워지는 순간이 오브젝트의 종료 //! 시점입니다. 다만 한 번의 호출 안에서의 순서는 보장하지 않습니다. 조상을 @@ -181,6 +183,8 @@ pub enum CapError { BadBadge, /// 파생 깊이 상한 초과 TooDeep, + /// 크기 인자가 0 + BadSize, /// 호출자의 메모리 준비(별칭 매핑/소거) 실패 PrepFailed, /// 부트스트랩 입력 구간이 잘못됨 @@ -707,6 +711,93 @@ pub unsafe fn retype( Ok(()) } +/// untyped에서 더 작은 자식 untyped를 잘라내는 함수입니다. +/// +/// 자리는 [retype]과 같은 규칙으로 정합니다. 워터마크를 그래뉼로 올림 정렬한 +/// 위치에서 `granules`개의 그래뉼을 잘라내고, 부모에 자손이 하나도 없으면 +/// 워터마크를 처음으로 되돌린 뒤에 자릅니다. 자식은 부모의 워터마크 아래에 +/// 놓인 자손이므로 부모는 자식이 살아 있는 동안 그 구간을 다시 내주지 +/// 않습니다. 자식의 마지막 그래뉼까지 오브젝트가 될 수 있어야 하므로 자식에서 +/// 나오는 오브젝트의 수는 정확히 `granules`입니다. 자식은 원본 표시를 달고 +/// 부모 바로 뒤에 깊이 + 1로 들어갑니다. untyped는 복사할 수 없으므로 한 +/// 구간의 워터마크는 언제나 하나입니다. +/// +/// 메모리는 읽지도 쓰지도 않고 커널 자원도 쓰지 않습니다. 모든 검사는 첫 +/// 기록보다 앞에 있어서 실패 경로에서는 상태가 일절 변하지 않습니다. +/// +/// # Arguments +/// `ut` - 원본 untyped가 든 슬롯 +/// `dest` - 자식 untyped를 받을 빈 슬롯 +/// `granules` - 자식의 크기(그래뉼 수, 1 이상) +/// `granule` - 플랫폼 그래뉼(2의 거듭제곱) +/// +/// # Errors +/// untyped 아님은 `NotUntyped`, 목적지 점유는 `Occupied`, 크기 0은 `BadSize`, +/// 공간 부족과 산술 넘침은 `Exhausted`, 깊이 초과는 `TooDeep` +/// +/// # Safety +/// 두 슬롯 모두 [read]의 조건을 만족해야 합니다. +pub unsafe fn split(ut: *mut Slot, dest: *mut Slot, granules: u64, granule: u64) -> Result<(), CapError> { + // SAFETY: 함수 계약을 중계함 + let src = unsafe { read(ut) }?.ok_or(CapError::NotUntyped)?; + let Cap::Untyped { base, size, used } = src.cap else { + return Err(CapError::NotUntyped); + }; + // SAFETY: 함수 계약을 중계함 + if unsafe { read(dest) }?.is_some() { + return Err(CapError::Occupied); + } + if granules == 0 { + return Err(CapError::BadSize); + } + if granule < SLOT_SIZE as u64 || !granule.is_power_of_two() { + return Err(CapError::Exhausted); + } + // 자손이 없으면 이 구간에 살아 있는 것이 없으므로 처음부터 다시 자름 + // SAFETY: 함수 계약을 중계함 + let used = if unsafe { has_descendants(ut) } { used } else { 0 }; + + let mark = base.checked_add(used).ok_or(CapError::Exhausted)?; + let carve = mark.checked_add(granule - 1).ok_or(CapError::Exhausted)? & !(granule - 1); + let bytes = granules.checked_mul(granule).ok_or(CapError::Exhausted)?; + let carve_end = carve.checked_add(bytes).ok_or(CapError::Exhausted)?; + let end = base.checked_add(size).ok_or(CapError::Corrupt)?; + if carve_end > end { + return Err(CapError::Exhausted); + } + // 자식의 마지막 그래뉼도 오브젝트의 PA로 인코딩될 수 있어야 함. 그래야 + // 자식의 그래뉼 수가 곧 거기서 나오는 오브젝트의 수임 + if (carve_end - granule) & !BASE_MASK != 0 { + return Err(CapError::Exhausted); + } + // SAFETY: 함수 계약대로 ut는 유효함 + let depth = unsafe { (*ut).depth } + .checked_add(1) + .filter(|d| *d <= MAX_DEPTH) + .ok_or(CapError::TooDeep)?; + + // 확정: 부모의 워터마크를 자식 뒤로 옮기고 자식을 기록 + // SAFETY: 함수 계약을 중계함, 종류와 base가 같은 갱신임 + unsafe { + update( + ut, + Cap::Untyped { + base, + size, + used: carve_end - base, + }, + )?; + let w = encode(&Cap::Untyped { + base: carve, + size: bytes, + used: 0, + }); + (*dest).w = [w[0] | FLAG_ORIGINAL, w[1], w[2], w[3]]; + link_after(ut, dest, depth); + } + Ok(()) +} + /// 케이퍼빌리티를 다른 슬롯으로 복사(파생)하는 함수입니다. /// /// 복사본은 원본 슬롯의 자식으로 리스트에 들어가므로 원본을 회수하거나 diff --git a/crates/k0-cap/src/tests.rs b/crates/k0-cap/src/tests.rs index ec1df45..943a7ba 100644 --- a/crates/k0-cap/src/tests.rs +++ b/crates/k0-cap/src/tests.rs @@ -1216,6 +1216,591 @@ fn deeply_nested_cnodes_are_destroyed_iteratively() { }); } +// 분할: untyped에서 더 작은 untyped를 잘라냄 + +#[test] +fn split_carves_an_aligned_child_and_moves_the_parents_watermark() { + for g in [4096u64, 16384] { + // 구간의 시작이 그래뉼 경계가 아니어도 자식은 경계에서 시작함 + let (c, next) = filled(&[r(0x4000_0800, 40 * g)], &[]); + let n = next as usize; + let ut = unsafe { c.add(UT) }; + let Cap::Untyped { base, size, used: 0 } = cap_at(c, UT) else { + unreachable!() + }; + let first = base.next_multiple_of(g); + unsafe { + split(ut, c.add(n), 5, g).unwrap(); + let e = get(c, n).unwrap(); + assert_eq!(e.cap, Cap::Untyped { base: first, size: 5 * g, used: 0 }); + assert!(e.original && !e.bound); + assert_eq!(((*c.add(n)).prev, (*c.add(n)).depth), (ut as u64, 1)); + assert_eq!((*ut).next, c.add(n) as u64); + assert_eq!(cap_at(c, UT), Cap::Untyped { base, size, used: first + 5 * g - base }); + // 다음 것은 오브젝트든 자식이든 그 자식 바로 뒤에서 나옴 + retype(ut, c.add(n + 1), ObjKind::Frame, g, |pa| (pa == first + 5 * g).then_some(0)).unwrap(); + split(ut, c.add(n + 2), 2, g).unwrap(); + assert_eq!(cap_at(c, n + 2), Cap::Untyped { base: first + 6 * g, size: 2 * g, used: 0 }); + // 가장 새 자식이 부모 바로 뒤에 놓임 + assert_eq!((*ut).next, c.add(n + 2) as u64); + assert_eq!(cap_at(c, UT), Cap::Untyped { base, size, used: first + 8 * g - base }); + } + } +} + +#[test] +fn split_refusals_change_nothing() { + for g in [4096u64, 16384] { + let (c, next) = filled(&[r(0x4000_0000, 8 * g)], &[]); + let n = next as usize; + let ut = unsafe { c.add(UT) }; + let state = |s: *mut Slot| unsafe { ((*s).w, (*s).prev, (*s).next, (*s).depth, (*s).aux) }; + unsafe { + // 워터마크가 처음이 아닌 상태에서 봄(일곱 그래뉼이 남음) + retype(ut, c.add(n), ObjKind::Frame, g, ok_prep).unwrap(); + let all = || (state(ut), state(c.add(n)), state(c.add(n + 1)), state(c.add(n + 2))); + let before = all(); + let console = c.add(boot_slot::CONSOLE as usize); + let cases = [ + (ut, c.add(n + 1), 0, CapError::BadSize), + (ut, c.add(n + 1), 8, CapError::Exhausted), + (ut, c.add(n + 1), u64::MAX, CapError::Exhausted), + // 그래뉼 수와 그래뉼의 곱이 64비트를 넘음 + (ut, c.add(n + 1), u64::MAX / g + 1, CapError::Exhausted), + // 곱은 들어가지만 구간보다 훨씬 큼 + (ut, c.add(n + 1), (1 << 62) / g, CapError::Exhausted), + (ut, c.add(n), 1, CapError::Occupied), + (ut, ut, 1, CapError::Occupied), + (c.add(n + 1), c.add(n + 2), 1, CapError::NotUntyped), + (c.add(n), c.add(n + 1), 1, CapError::NotUntyped), + (console, c.add(n + 1), 1, CapError::NotUntyped), + ]; + for (src, dst, count, want) in cases { + assert_eq!(split(src, dst, count, g), Err(want), "{count} granules"); + assert_eq!(all(), before, "a refused split changed a slot"); + } + // 검사 순서: 원본의 종류, 목적지, 크기 + assert_eq!(split(c.add(n), c.add(n), 0, g), Err(CapError::NotUntyped)); + assert_eq!(split(ut, c.add(n), 0, g), Err(CapError::Occupied)); + // 그래뉼이 2의 거듭제곱이 아니거나 슬롯보다 작으면 아무것도 자르지 않음 + assert_eq!(split(ut, c.add(n + 1), 1, 3000), Err(CapError::Exhausted)); + assert_eq!(split(ut, c.add(n + 1), 1, 32), Err(CapError::Exhausted)); + assert_eq!(all(), before); + // 남은 것 전부는 내줄 수 있고, 그 뒤에는 아무것도 남지 않음 + split(ut, c.add(n + 1), 7, g).unwrap(); + assert_eq!(cap_at(c, n + 1), Cap::Untyped { base: 0x4000_0000 + g, size: 7 * g, used: 0 }); + assert_eq!(split(ut, c.add(n + 2), 1, g), Err(CapError::Exhausted)); + assert_eq!( + retype(ut, c.add(n + 2), ObjKind::Frame, g, |_| panic!("prep must not run")), + Err(CapError::Exhausted) + ); + } + } +} + +#[test] +fn split_near_the_top_of_the_address_space_does_not_overflow() { + let c = node(8); + unsafe { + // 워터마크를 올림 정렬하는 덧셈이 넘침 + let low = Cap::Untyped { base: u64::MAX - G + 2, size: G - 2, used: 0 }; + insert_root(c.add(1), low).unwrap(); + for count in [1, 2, u64::MAX / G, u64::MAX] { + assert_eq!(split(c.add(1), c.add(2), count, G), Err(CapError::Exhausted)); + } + assert_eq!((get(c, 2), cap_at(c, 1)), (None, low)); + + // 정렬은 되지만 자식의 끝이 넘치거나 인코딩 범위 밖임 + let top = Cap::Untyped { base: u64::MAX - 4 * G + 1, size: 4 * G - 1, used: 0 }; + insert_root(c.add(3), top).unwrap(); + for count in [1, 3, 4, 5, u64::MAX / G] { + assert_eq!(split(c.add(3), c.add(4), count, G), Err(CapError::Exhausted)); + } + assert_eq!((get(c, 4), cap_at(c, 3)), (None, top)); + } +} + +#[test] +fn a_child_beyond_the_encodable_range_is_refused() { + let c = node(8); + unsafe { + // 오브젝트의 주소로 쓸 수 있는 마지막 두 그래뉼과 그 뒤의 두 그래뉼 + let top = 1u64 << 48; + insert_root(c.add(1), Cap::Untyped { base: top - 2 * G, size: 4 * G, used: 0 }).unwrap(); + // 마지막 그래뉼이 오브젝트가 될 수 없는 자식은 만들지 않음 + assert_eq!(split(c.add(1), c.add(2), 3, G), Err(CapError::Exhausted)); + assert_eq!(split(c.add(1), c.add(2), 4, G), Err(CapError::Exhausted)); + assert_eq!(get(c, 2), None); + // 범위 안의 둘은 자를 수 있고, 거기서 정확히 오브젝트 둘이 나옴 + split(c.add(1), c.add(2), 2, G).unwrap(); + retype(c.add(2), c.add(3), ObjKind::Frame, G, |pa| (pa == top - 2 * G).then_some(0)).unwrap(); + retype(c.add(2), c.add(4), ObjKind::Frame, G, |pa| (pa == top - G).then_some(0)).unwrap(); + assert_eq!( + retype(c.add(2), c.add(5), ObjKind::Frame, G, |_| panic!("prep must not run")), + Err(CapError::Exhausted) + ); + // 부모에 남은 두 그래뉼은 오브젝트도 자식도 될 수 없음 + assert_eq!(split(c.add(1), c.add(5), 1, G), Err(CapError::Exhausted)); + assert_eq!( + retype(c.add(1), c.add(5), ObjKind::Frame, G, |_| panic!("prep must not run")), + Err(CapError::Exhausted) + ); + } +} + +#[test] +fn a_child_yields_exactly_its_granules_and_the_parent_keeps_the_rest() { + for g in [4096u64, 16384] { + let (c, next) = filled(&[r(0x4000_0000, 12 * g)], &[]); + let n = next as usize; + let ut = unsafe { c.add(UT) }; + unsafe { + split(ut, c.add(n), 5, g).unwrap(); + let child = c.add(n); + let mut seen = Vec::new(); + for i in 0..5 { + retype(child, c.add(n + 1 + i), ObjKind::Frame, g, |pa| { + seen.push(pa); + Some(0) + }) + .unwrap(); + } + assert_eq!(seen, (0..5).map(|i| 0x4000_0000 + i * g).collect::>()); + assert_eq!( + retype(child, c.add(n + 6), ObjKind::Frame, g, |_| panic!("prep must not run")), + Err(CapError::Exhausted) + ); + assert_eq!(split(child, c.add(n + 6), 1, g), Err(CapError::Exhausted)); + // 자식이 다 찼어도 부모에는 나머지 일곱이 그대로 있음 + let mut rest = Vec::new(); + for i in 0..7 { + retype(ut, c.add(n + 6 + i), ObjKind::Frame, g, |pa| { + rest.push(pa); + Some(0) + }) + .unwrap(); + } + assert_eq!(rest, (5..12).map(|i| 0x4000_0000 + i * g).collect::>()); + assert_eq!( + retype(ut, c.add(n + 13), ObjKind::Frame, g, |_| panic!("prep must not run")), + Err(CapError::Exhausted) + ); + } + } +} + +#[test] +fn children_and_objects_of_one_parent_never_overlap() { + let mut rng = Rng(0x6A09_E667_F3BC_C908); + let (mut cuts, mut frames) = (0, 0); + for g in [4096u64, 16384] { + for _ in 0..200 { + let memory = [r(0x4000_0000 + rng.below(3) * 0x800, g * (8 + rng.below(40)))]; + let (c, next) = filled_n(160, &memory, &[]); + let Cap::Untyped { base, size, .. } = cap_at(c, UT) else { + unreachable!() + }; + // (슬롯, 구간의 시작과 끝, 거기서 잘라낸 구간들) + let mut uts = vec![(UT, base, base + size, Vec::<(u64, u64)>::new())]; + let mut objects = Vec::new(); + let mut dest = next as usize; + for _ in 0..120 { + let k = rng.below(uts.len() as u64) as usize; + let (slot, lo, hi) = (uts[k].0, uts[k].1, uts[k].2); + let (from, to) = if rng.below(3) == 0 { + let count = 1 + rng.below(4); + match unsafe { split(c.add(slot), c.add(dest), count, g) } { + Ok(()) => { + let Cap::Untyped { base, size, used } = cap_at(c, dest) else { + unreachable!() + }; + assert_eq!((size, used), (count * g, 0)); + uts.push((dest, base, base + size, Vec::new())); + cuts += 1; + (base, base + size) + } + Err(CapError::Exhausted) => continue, + Err(e) => panic!("unexpected {e:?}"), + } + } else { + let mut at = None; + match unsafe { + retype(c.add(slot), c.add(dest), ObjKind::Frame, g, |pa| { + at = Some(pa); + Some(0) + }) + } { + Ok(()) => { + let pa = at.unwrap(); + objects.push(pa); + frames += 1; + (pa, pa + g) + } + Err(CapError::Exhausted) => continue, + Err(e) => panic!("unexpected {e:?}"), + } + }; + dest += 1; + assert!(from % g == 0 && from >= lo && to <= hi, "a carve left its untyped"); + assert!(uts[k].3.iter().all(|&(a, b)| to <= a || from >= b), "two carves of one untyped overlap"); + uts[k].3.push((from, to)); + } + // 어느 untyped에서 나왔든 오브젝트끼리는 겹치지 않음 + objects.sort_unstable(); + assert!(objects.windows(2).all(|w| w[0] + g <= w[1]), "two objects share a granule"); + } + } + assert!(cuts > 2_000 && frames > 5_000, "only {cuts} splits and {frames} objects"); +} + +#[test] +fn revoking_a_child_restarts_the_child_and_not_the_parent() { + for g in [4096u64, 16384] { + let (c, next) = filled(&[r(0x4000_0000, 12 * g)], &[]); + let n = next as usize; + let ut = unsafe { c.add(UT) }; + let mut log = Log::default(); + unsafe { + retype(ut, c.add(n), ObjKind::Frame, g, ok_prep).unwrap(); + split(ut, c.add(n + 1), 4, g).unwrap(); + let child = c.add(n + 1); + for i in 0..4 { + retype(child, c.add(n + 2 + i), ObjKind::Endpoint, g, ok_prep).unwrap(); + } + copy(c.add(n + 2), c.add(n + 6), rights::R, 0, false).unwrap(); + let parent = (*ut).w; + revoke(child, &mut log).unwrap(); + // 자식 아래의 것만 사라짐: 원본 넷과 사본 하나 + assert_eq!(log.removed.len(), 5); + assert_eq!(log.removed.iter().filter(|r| r.1).count(), 4); + for i in 2..7 { + assert_eq!(get(c, n + i), None); + } + // 자식은 남고, 부모의 워터마크와 부모의 다른 자식은 그대로임 + assert!(get(c, n + 1).is_some() && get(c, n).is_some()); + assert_eq!((*ut).w, parent); + assert!(!has_descendants(child) && has_descendants(ut)); + // 자식은 자기 구간의 처음부터 다시 나가고, 부모는 자식 뒤에서 이어짐 + retype(child, c.add(n + 2), ObjKind::Tcb, g, |pa| (pa == 0x4000_0000 + g).then_some(0)).unwrap(); + retype(ut, c.add(n + 3), ObjKind::Frame, g, |pa| (pa == 0x4000_0000 + 5 * g).then_some(0)).unwrap(); + } + } +} + +#[test] +fn deleting_a_child_returns_nothing_until_the_parent_is_empty() { + for g in [4096u64, 16384] { + let (c, next) = filled(&[r(0x4000_0000, 6 * g)], &[]); + let n = next as usize; + let ut = unsafe { c.add(UT) }; + let mut log = Log::default(); + let full = |dest: *mut Slot| unsafe { + retype(ut, dest, ObjKind::Frame, g, |_| panic!("prep must not run")) == Err(CapError::Exhausted) + && split(ut, dest, 1, g) == Err(CapError::Exhausted) + }; + unsafe { + retype(ut, c.add(n), ObjKind::Frame, g, ok_prep).unwrap(); + split(ut, c.add(n + 1), 4, g).unwrap(); + retype(ut, c.add(n + 2), ObjKind::Frame, g, ok_prep).unwrap(); + assert!(full(c.add(n + 3))); + retype(c.add(n + 1), c.add(n + 3), ObjKind::Frame, g, ok_prep).unwrap(); + delete(c.add(n + 1), &mut log).unwrap(); + assert_eq!((get(c, n + 1), get(c, n + 3)), (None, None)); + // 자식의 네 그래뉼은 부모에게 돌아오지 않음 + assert!(full(c.add(n + 3))); + delete(c.add(n), &mut log).unwrap(); + assert!(full(c.add(n + 3)), "one object of the parent is still alive"); + // 부모에서 나온 것이 하나도 남지 않으면 전부가 한꺼번에 돌아옴 + delete(c.add(n + 2), &mut log).unwrap(); + split(ut, c.add(n + 3), 6, g).unwrap(); + assert_eq!(cap_at(c, n + 3), Cap::Untyped { base: 0x4000_0000, size: 6 * g, used: 0 }); + } + } +} + +#[test] +fn a_child_cannot_be_copied_and_moves_with_its_subtree() { + let (c, next) = filled(&[r(0x4000_0000, 8 * G)], &[]); + let n = next as usize; + let other = node(16); + let mut log = Log::default(); + unsafe { + let ut = c.add(UT); + split(ut, c.add(n), 4, G).unwrap(); + // 구간마다 워터마크는 하나: 사본을 만들 수 없음 + assert_eq!(copy(c.add(n), c.add(n + 1), rights::ALL, 0, false), Err(CapError::NotCopyable)); + assert_eq!(copy(c.add(n), c.add(n + 1), rights::ALL, 0, true), Err(CapError::NotCopyable)); + assert_eq!(get(c, n + 1), None); + retype(c.add(n), c.add(n + 1), ObjKind::Endpoint, G, ok_prep).unwrap(); + split(c.add(n), c.add(n + 2), 1, G).unwrap(); + // 다른 CNode로 옮기면 워터마크와 깊이와 자손이 그대로 따라감 + let before = get(c, n); + move_cap(c.add(n), other.add(5)).unwrap(); + assert_eq!(get(c, n), None); + assert_eq!(get(other, 5), before); + assert_eq!((*other.add(5)).depth, 1); + assert!(has_descendants(other.add(5))); + // 옮긴 자리에서 이어서 잘라냄 + retype(other.add(5), other.add(6), ObjKind::Frame, G, |pa| (pa == 0x4000_0000 + 2 * G).then_some(0)).unwrap(); + // 부모를 회수하면 옮겨 간 자식과 그 아래의 것이 전부 사라짐 + revoke(ut, &mut log).unwrap(); + assert_eq!((get(other, 5), get(other, 6), get(c, n + 1), get(c, n + 2)), (None, None, None, None)); + assert_eq!(log.removed.len(), 4); + } +} + +#[test] +fn revoking_an_ancestor_removes_nested_children_and_their_objects() { + let (c, next) = filled(&[r(0x4000_0000, 16 * G)], &[]); + let n = next as usize; + let mut log = Log::default(); + unsafe { + let ut = c.add(UT); + // A는 여덟 그래뉼, B는 A의 앞쪽 넷, C는 B 전체. 셋 다 같은 자리에서 시작함 + split(ut, c.add(n), 8, G).unwrap(); + split(c.add(n), c.add(n + 1), 4, G).unwrap(); + split(c.add(n + 1), c.add(n + 2), 4, G).unwrap(); + assert_eq!(cap_at(c, n + 1), Cap::Untyped { base: 0x4000_0000, size: 4 * G, used: 4 * G }); + assert_eq!(cap_at(c, n + 2), Cap::Untyped { base: 0x4000_0000, size: 4 * G, used: 0 }); + assert_eq!(((*c.add(n)).depth, (*c.add(n + 1)).depth, (*c.add(n + 2)).depth), (1, 2, 3)); + // 전부를 내준 B는 더 자를 수 없고, 같은 구간의 C만 자를 수 있음 + assert_eq!( + retype(c.add(n + 1), c.add(n + 3), ObjKind::Frame, G, |_| panic!("prep must not run")), + Err(CapError::Exhausted) + ); + retype(c.add(n + 2), c.add(n + 3), ObjKind::Frame, G, |pa| (pa == 0x4000_0000).then_some(0)).unwrap(); + retype(c.add(n), c.add(n + 4), ObjKind::Frame, G, |pa| (pa == 0x4000_0000 + 4 * G).then_some(0)).unwrap(); + // A를 회수하면 B, C와 두 프레임이 사라지고 A는 남음 + revoke(c.add(n), &mut log).unwrap(); + for i in 1..5 { + assert_eq!(get(c, n + i), None); + } + assert_eq!(log.removed.len(), 4); + assert!(log.removed.iter().all(|r| r.1 && !r.2)); + assert_eq!(log.removed.iter().filter(|r| matches!(r.0, Cap::Untyped { .. })).count(), 2); + assert!(get(c, n).is_some() && !has_descendants(c.add(n)) && has_descendants(ut)); + // 맨 위를 삭제하면 A도 사라짐 + delete(ut, &mut log).unwrap(); + assert_eq!((get(c, n), get(c, UT)), (None, None)); + } +} + +#[test] +fn split_depth_is_bounded() { + let (c, _) = filled(&[r(0x4000_0000, 16 * G)], &[]); + unsafe { + (*c.add(UT)).depth = MAX_DEPTH; + let before = (*c.add(UT)).w; + assert_eq!(split(c.add(UT), c.add(20), 1, G), Err(CapError::TooDeep)); + assert_eq!(get(c, 20), None); + assert_eq!((*c.add(UT)).w, before); + // 상한에 닿는 자식까지는 만들 수 있고, 그 자식은 더 자를 수 없음 + (*c.add(UT)).depth = MAX_DEPTH - 1; + split(c.add(UT), c.add(20), 2, G).unwrap(); + assert_eq!((*c.add(20)).depth, MAX_DEPTH); + assert_eq!(split(c.add(20), c.add(21), 1, G), Err(CapError::TooDeep)); + assert_eq!( + retype(c.add(20), c.add(21), ObjKind::Frame, G, |_| panic!("prep must not run")), + Err(CapError::TooDeep) + ); + assert_eq!(get(c, 21), None); + } +} + +#[test] +fn removing_a_child_untyped_reports_it_once_as_an_original() { + let (c, next) = filled(&[r(0x4000_0000, 8 * G)], &[]); + let n = next as usize; + let mut log = Log::default(); + unsafe { + split(c.add(UT), c.add(n), 3, G).unwrap(); + retype(c.add(n), c.add(n + 1), ObjKind::Frame, G, ok_prep).unwrap(); + delete(c.add(n), &mut log).unwrap(); + // 프레임 하나와 자식 untyped 하나, 각각 한 번씩 + assert_eq!(log.removed.len(), 2); + let child = Cap::Untyped { base: 0x4000_0000, size: 3 * G, used: G }; + assert_eq!(log.removed.iter().filter(|r| r.0 == child).collect::>(), [&(child, true, false)]); + // 이미 사라진 슬롯을 다시 지워도 아무것도 알리지 않음 + delete(c.add(n), &mut log).unwrap(); + assert_eq!(log.removed.len(), 2); + } +} + +#[test] +fn the_supervisor_recipe_reuses_the_slab_in_place() { + for g in [4096u64, 16384] { + let mut w = World::with(g, 32); + let root = w.root(); + let at = |i: u64| 0x4000_0000 + i * g; + unsafe { + // 슬랩은 감독자의 CNode에 남음 + w.cut(root.add(UT), root.add(10), 16); + let slab = root.add(10); + for round in 0..3 { + // 서비스의 뼈대: CNode, TCB, 주소 공간. TCB는 둘에 묶임 + let (c_pa, c) = w.make(slab, root.add(11), ObjKind::CNode); + let (t_pa, t) = w.make(slab, root.add(12), ObjKind::Tcb); + let (a_pa, _) = w.make(slab, root.add(13), ObjKind::AddrSpace); + copy_pair_bound(root.add(11), t.add(1), root.add(13), t.add(2)).unwrap(); + // 예산: 슬랩의 나머지에서 잘라 서비스의 CNode로 옮김 + w.cut(slab, root.add(14), 8); + move_cap(root.add(14), c.add(2)).unwrap(); + // 서비스가 예산으로 하는 일: 오브젝트, 사본, 다시 자르기 + let (f_pa, _) = w.make(c.add(2), c.add(3), ObjKind::Frame); + copy(c.add(3), c.add(4), rights::R, 0, false).unwrap(); + w.cut(c.add(2), c.add(5), 2); + let (e_pa, _) = w.make(c.add(5), c.add(6), ObjKind::Endpoint); + w.check(); + // 회차마다 같은 자리가 나옴 + assert_eq!([c_pa, t_pa, a_pa, f_pa, e_pa], [0, 1, 2, 3, 4].map(at), "round {round}"); + // 슬랩에는 뼈대 셋과 예산 여덟 뒤의 다섯이 남아 있음 + let (rest, _) = w.make(slab, root.add(15), ObjKind::Frame); + assert_eq!(rest, at(11)); + // 재시작: 슬랩을 회수하면 한 번에 전부 사라지고 슬랩은 남음 + revoke(slab, &mut w).unwrap(); + w.check(); + for pa in [c_pa, t_pa, a_pa, f_pa, e_pa, rest] { + assert!(!w.objs.contains(&(2, pa)), "round {round}"); + } + assert!(w.torn.contains(&(t as u64))); + assert!(read(slab).unwrap().is_some() && !has_descendants(slab)); + for i in 11..16 { + assert_eq!(get(root, i), None); + } + assert_eq!(w.uts.get(&(at(0), 16 * g)), Some(&1)); + assert!(!w.uts.contains_key(&(at(3), 8 * g)), "the budget went with the slab"); + } + // 슬랩 밖의 부모는 슬랩 뒤에서 이어짐 + let (pa, _) = w.make(root.add(UT), root.add(11), ObjKind::Frame); + assert_eq!(pa, at(16)); + w.check(); + } + } +} + +#[test] +fn revoking_a_child_parked_under_itself_deletes_it() { + for g in [4096u64, 16384] { + let mut w = World::with(g, 16); + let root = w.root(); + unsafe { + // 자식에서 CNode를 만들고 자식 자신을 그 안에 둠 + w.cut(root.add(UT), root.add(10), 4); + let (y_pa, y) = w.make(root.add(10), root.add(11), ObjKind::CNode); + move_cap(root.add(10), y.add(2)).unwrap(); + w.check(); + // 그 슬롯으로 회수: CNode가 종료되고, 그 안을 비우면서 자식도 삭제됨 + revoke(y.add(2), &mut w).unwrap(); + w.check(); + assert!(!w.objs.contains(&(2, y_pa))); + assert!(read(y.add(2)).unwrap().is_none(), "the child was deleted by its own revoke"); + assert!(!w.uts.contains_key(&(0x4000_0000, 4 * g))); + // 부모에는 자손이 없으므로 처음부터 다시 나감 + assert!(!has_descendants(root.add(UT))); + let (pa, _) = w.make(root.add(UT), root.add(10), ObjKind::Frame); + assert_eq!(pa, 0x4000_0000); + w.check(); + } + } +} + +#[test] +fn revoking_a_child_deletes_a_parent_parked_under_it() { + for g in [4096u64, 16384] { + let mut w = World::with(g, 16); + let root = w.root(); + unsafe { + // 슬랩에서 예산을 자르고, 예산에서 만든 CNode 안에 슬랩을 둠 + w.cut(root.add(UT), root.add(10), 8); + w.cut(root.add(10), root.add(11), 4); + let (f_pa, _) = w.make(root.add(10), root.add(12), ObjKind::Frame); + let (y_pa, y) = w.make(root.add(11), root.add(13), ObjKind::CNode); + move_cap(root.add(10), y.add(3)).unwrap(); + w.check(); + // 예산을 회수: CNode가 종료되면서 그 안의 슬랩이 삭제되고, 슬랩의 + // 자손인 예산 자신과 슬랩의 다른 자식도 함께 사라짐 + revoke(root.add(11), &mut w).unwrap(); + w.check(); + assert!(!w.objs.contains(&(2, y_pa)) && !w.objs.contains(&(2, f_pa))); + assert!(read(root.add(11)).unwrap().is_none(), "the revoked child went with its parent"); + assert_eq!(w.uts.len(), 2, "only the boot untypeds are left"); + assert!(!has_descendants(root.add(UT))); + } + } +} + +#[test] +fn scrubbing_a_revoked_child_needs_its_granules_held() { + for g in [4096u64, 16384] { + let (c, next) = filled(&[r(0x4000_0000, 12 * g)], &[]); + let n = next as usize; + let mut log = Log::default(); + let first = 0x4000_0000 + g; + unsafe { + let ut = c.add(UT); + retype(ut, c.add(n), ObjKind::Frame, g, ok_prep).unwrap(); + split(ut, c.add(n + 1), 6, g).unwrap(); + let slab = c.add(n + 1); + // 하나씩 만들고 지우면 그때마다 자손이 없어져 첫 그래뉼만 다시 나옴 + for _ in 0..6 { + retype(slab, c.add(n + 2), ObjKind::Frame, g, |pa| (pa == first).then_some(0)).unwrap(); + delete(c.add(n + 2), &mut log).unwrap(); + } + // 전부 쥔 채로 만들면 그래뉼마다 한 번씩, 정확히 여섯 번 나오고 끝남 + let mut seen = Vec::new(); + for i in 0..6 { + retype(slab, c.add(n + 2 + i), ObjKind::Frame, g, |pa| { + seen.push(pa); + Some(0) + }) + .unwrap(); + } + assert_eq!(seen, (0..6).map(|i| first + i * g).collect::>()); + assert_eq!( + retype(slab, c.add(n + 8), ObjKind::Frame, g, |_| panic!("prep must not run")), + Err(CapError::Exhausted) + ); + // 하나를 쥐고 나머지를 하나씩 만들고 지워도 끝까지 감 + revoke(slab, &mut log).unwrap(); + retype(slab, c.add(n + 2), ObjKind::Frame, g, |pa| (pa == first).then_some(0)).unwrap(); + for i in 1..6 { + retype(slab, c.add(n + 3), ObjKind::Frame, g, |pa| (pa == first + i * g).then_some(0)).unwrap(); + delete(c.add(n + 3), &mut log).unwrap(); + } + assert_eq!( + retype(slab, c.add(n + 3), ObjKind::Frame, g, |_| panic!("prep must not run")), + Err(CapError::Exhausted) + ); + } + } +} + +#[test] +fn a_very_deep_chain_of_nested_children_is_deleted_iteratively() { + on_small_stack(|| { + const N: usize = 60_000; + let c = node(N + 8); + let mut log = Log::default(); + unsafe { + // 그래뉼 하나짜리 untyped를 층마다 통째로 자식에게 줌 + insert_root(c.add(1), Cap::Untyped { base: 0x4000_0000, size: G, used: 0 }).unwrap(); + for i in 1..N { + split(c.add(i), c.add(i + 1), 1, G).unwrap(); + } + assert_eq!((*c.add(N)).depth, N as u64 - 1); + // 오브젝트는 맨 아래 것에서만 나옴 + assert_eq!( + retype(c.add(1), c.add(N + 1), ObjKind::Frame, G, |_| panic!("prep must not run")), + Err(CapError::Exhausted) + ); + retype(c.add(N), c.add(N + 1), ObjKind::Frame, G, ok_prep).unwrap(); + delete(c.add(1), &mut log).unwrap(); + } + assert_eq!(log.removed.len(), N + 1); + assert_eq!((get(c, N), get(c, N + 1)), (None, None)); + }); +} + // 무작위 연산열에 대한 모델 검사 const ROOT_N: usize = 48; @@ -1256,6 +1841,16 @@ struct World { /// 한 번이라도 오브젝트였던 PA와, 그런 자리를 다시 잘라낸 횟수 ever: BTreeSet, reused: u64, + /// 살아 있는 untyped: (base, size) -> 그 구간을 가리키는 케이퍼빌리티 수. + /// 자식이 부모와 같은 자리에서 시작하거나 부모 전체를 차지할 수 있어서 + /// 주소만으로는 구별되지 않음 + uts: BTreeMap<(u64, u64), u32>, + /// 성공한 분할, 그중 자식을 다시 자른 것 + splits: u64, + nested: u64, + /// 자식 untyped에서 만든 오브젝트, 그중 전에 쓰인 자리를 다시 쓴 것 + child_objs: u64, + child_reused: u64, } impl Env for World { @@ -1279,7 +1874,15 @@ impl Env for World { self.torn.insert(owner.0 as u64); } if r.original { - assert!(self.objs.remove(&ident(&r.cap)), "object finalized twice: {:?}", r.cap); + if let Cap::Untyped { base, size, .. } = r.cap { + let n = self.uts.get_mut(&(base, size)).expect("an untyped that was never made is removed"); + *n -= 1; + if *n == 0 { + self.uts.remove(&(base, size)); + } + } else { + assert!(self.objs.remove(&ident(&r.cap)), "object finalized twice: {:?}", r.cap); + } self.finalized += 1; } } @@ -1304,6 +1907,11 @@ impl World { r(0x5000_0000, granule * (2 + rng.below(6))), ]; unsafe { bootstrap(&cref(root, ROOT_N), &BOOT, &memory, &[]) }.unwrap(); + World::adopt(granule, root) + } + + /// 부트스트랩을 마친 루트 CNode에서 모형을 만드는 함수입니다. + fn adopt(granule: u64, root: *mut Slot) -> Self { let mut w = World { granule, containers: BTreeMap::new(), @@ -1313,13 +1921,24 @@ impl World { finalized: 0, ever: BTreeSet::new(), reused: 0, + uts: BTreeMap::new(), + splits: 0, + nested: 0, + child_objs: 0, + child_reused: 0, }; w.containers.insert(BOOT.cnode, (root, ROOT_N)); // 루트 TCB도 슬롯을 담는 오브젝트 w.containers.insert(BOOT.tcb, (node(TCB_N), TCB_N)); for i in 1..ROOT_N { - if let Some(e) = get(root, i) { - w.objs.insert(ident(&e.cap)); + match get(root, i) { + Some(Entry { cap: Cap::Untyped { base, size, .. }, .. }) => { + *w.uts.entry((base, size)).or_default() += 1; + } + Some(e) => { + w.objs.insert(ident(&e.cap)); + } + None => {} } } w @@ -1373,11 +1992,69 @@ impl World { let empty = |e: Option| e.is_none(); let untyped = |e: Option| matches!(e, Some(Entry { cap: Cap::Untyped { .. }, .. })); match rng.below(100) { - 0..=39 => { + 0..=7 => { let (a, b) = (self.pick(rng, untyped), self.pick(rng, empty)); if a.is_null() || b.is_null() { return; } + let g = self.granule; + let (ea, eb) = unsafe { (read(a).unwrap(), read(b).unwrap()) }; + // 장부만으로 남은 그래뉼 수를 셈(자손이 없으면 처음부터) + let left = match ea { + Some(Entry { cap: Cap::Untyped { base, size, used }, .. }) => { + let used = if unsafe { has_descendants(a) } { used } else { 0 }; + (base + size).saturating_sub((base + used).next_multiple_of(g)) / g + } + _ => 0, + }; + let n = match rng.below(10) { + 0 => 0, + 1 | 2 => left, + 3 => left + 1 + rng.below(3), + 4 => u64::MAX / g + 1, + _ => 1 + rng.below(3), + }; + let expect = match ea { + Some(Entry { cap: Cap::Untyped { .. }, .. }) => { + if eb.is_some() { + Err(CapError::Occupied) + } else if n == 0 { + Err(CapError::BadSize) + } else if n > left { + Err(CapError::Exhausted) + } else { + Ok(()) + } + } + _ => Err(CapError::NotUntyped), + }; + let state = |s: *mut Slot| unsafe { ((*s).w, (*s).prev, (*s).next, (*s).depth, (*s).aux) }; + let (before, level) = ((state(a), state(b)), unsafe { (*a).depth }); + let res = unsafe { split(a, b, n, g) }; + assert_eq!(res, expect, "split of {n} granules with {left} left"); + if res.is_err() { + assert_eq!((state(a), state(b)), before, "a refused split changes nothing"); + return; + } + let child = unsafe { read(b) }.unwrap().expect("the child exists"); + let Cap::Untyped { base, size, used } = child.cap else { + panic!("a split made {:?}", child.cap) + }; + assert!(child.original && !child.bound); + assert_eq!((size, used, base % g), (n * g, 0, 0)); + assert_eq!(unsafe { ((*b).prev, (*b).depth) }, (a as u64, level + 1)); + *self.uts.entry((base, size)).or_default() += 1; + self.splits += 1; + if level >= 1 { + self.nested += 1; + } + } + 8..=39 => { + let (a, b) = (self.pick(rng, untyped), self.pick(rng, empty)); + if a.is_null() || b.is_null() { + return; + } + let from_child = unsafe { (*a).depth } >= 1; let kind = [ ObjKind::Frame, ObjKind::PageTable, @@ -1399,10 +2076,15 @@ impl World { }; if res.is_ok() { let pa = at.unwrap(); - self.objs.insert((2, pa)); - if !self.ever.insert(pa) { + assert!(self.objs.insert((2, pa))); + let again = !self.ever.insert(pa); + if again { self.reused += 1; } + if from_child { + self.child_objs += 1; + self.child_reused += again as u64; + } match kind { ObjKind::CNode => { let n = (g / SLOT_SIZE as u64) as usize; @@ -1533,7 +2215,12 @@ impl World { }; filled += 1; assert_eq!(e.bound, n == TCB_N, "bound caps live exactly in TCB slots"); - assert!(self.objs.contains(&ident(&e.cap)), "cap to a dead object: {:?}", e.cap); + match e.cap { + Cap::Untyped { base, size, .. } => { + assert!(self.uts.contains_key(&(base, size)), "an untyped that was removed: {:?}", e.cap) + } + _ => assert!(self.objs.contains(&ident(&e.cap)), "cap to a dead object: {:?}", e.cap), + } let (p, nx, d) = unsafe { ((*s).prev, (*s).next, (*s).depth) }; if p == 0 { assert_eq!(d, 0); @@ -1553,8 +2240,10 @@ impl World { // 각 리스트를 머리부터 걸으며 전위 순서와 부모-자식 규칙을 확인 let mut visited = 0usize; let mut originals: BTreeMap<(u8, u64), u32> = BTreeMap::new(); + let mut untypeds: BTreeMap<(u64, u64), u32> = BTreeMap::new(); for head in heads { - let mut stack: Vec<(u64, Entry)> = Vec::new(); + // 깊이, 케이퍼빌리티, 그리고 untyped일 때 그 자식들이 차지한 구간 + let mut stack: Vec<(u64, Entry, Vec<(u64, u64)>)> = Vec::new(); let mut s = head; while !s.is_null() { visited += 1; @@ -1564,15 +2253,31 @@ impl World { while stack.last().is_some_and(|t| t.0 >= d) { stack.pop(); } - if let Some((pd, parent)) = stack.last() { + if let Some((pd, parent, taken)) = stack.last_mut() { assert_eq!(*pd + 1, d, "a child sits exactly one level below its parent"); match parent.cap { Cap::Untyped { base, used, .. } => { assert!(e.original, "an untyped's children are originals"); - let (class, pa) = ident(&e.cap); - assert_eq!(class, 2); - assert_eq!(pa % self.granule, 0); - assert!(pa >= base && pa + self.granule <= base + used, "object outside the consumed part"); + let g = self.granule; + let (lo, hi) = match e.cap { + // 자식 untyped: 온전한 그래뉼로만 이루어짐 + Cap::Untyped { base: cb, size: cs, .. } => { + assert!(cs >= g && cb % g == 0 && cs % g == 0, "a child untyped of partial granules"); + (cb, cb + cs) + } + _ => { + let (class, pa) = ident(&e.cap); + assert_eq!(class, 2); + assert_eq!(pa % g, 0); + (pa, pa + g) + } + }; + assert!(lo >= base && hi <= base + used, "a child outside the consumed part"); + // 한 untyped의 자식들은 서로 겹치지 않음 + for &(a, b) in taken.iter() { + assert!(hi <= a || lo >= b, "children of one untyped overlap"); + } + taken.push((lo, hi)); } _ => { assert!(!e.original, "a copy is never an original"); @@ -1593,10 +2298,15 @@ impl World { } else { assert_eq!(d, 0); } - if e.original { - *originals.entry(ident(&e.cap)).or_default() += 1; + match e.cap { + Cap::Untyped { base, size, .. } => { + assert!(e.original, "an untyped is never a copy"); + *untypeds.entry((base, size)).or_default() += 1; + } + _ if e.original => *originals.entry(ident(&e.cap)).or_default() += 1, + _ => {} } - stack.push((d, e)); + stack.push((d, e, Vec::new())); s = unsafe { (*s).next } as *mut Slot; } } @@ -1607,6 +2317,8 @@ impl World { assert_eq!(originals.get(o), Some(&1), "object {o:x?} must have exactly one original"); } assert_eq!(originals.len(), self.objs.len()); + // untyped는 장부에 적힌 수만큼만 있음 + assert_eq!(untypeds, self.uts); // 슬롯을 담는 오브젝트는 살아 있는 동안에만 배열을 가짐 for pa in self.containers.keys() { assert!(self.objs.contains(&(2, *pa))); @@ -1620,6 +2332,7 @@ fn random_operation_sequences_keep_every_invariant() { let mut finalized = 0; let mut torn = 0; let mut reused = 0; + let (mut splits, mut nested, mut child_objs, mut child_reused) = (0, 0, 0, 0); for round in 0..160 { let granule = if round % 2 == 0 { 4096 } else { 16384 }; let mut w = World::new(granule, &mut rng); @@ -1631,16 +2344,27 @@ fn random_operation_sequences_keep_every_invariant() { finalized += w.finalized; torn += w.torn.len(); reused += w.reused; + splits += w.splits; + nested += w.nested; + child_objs += w.child_objs; + child_reused += w.child_reused; } // 연산열이 실제로 종료 경로를 충분히 밟았는지 확인 assert!(finalized > 1_500, "only {finalized} objects were finalized"); assert!(torn > 20, "only {torn} TCBs lost a bound cap"); assert!(reused > 100, "only {reused} retypes reused reclaimed memory"); + // 분할도 마찬가지: 자식을 만들고, 자식을 다시 자르고, 자식에서 오브젝트를 + // 만들고, 비워진 자식의 자리를 다시 썼어야 함 + assert!(splits > 120, "only {splits} splits succeeded"); + assert!(nested > 20, "only {nested} splits cut a child again"); + assert!(child_objs > 150, "only {child_objs} objects came from a child untyped"); + assert!(child_reused > 50, "only {child_reused} retypes reused a child's memory"); } #[test] fn revoking_every_untyped_empties_the_world() { let mut rng = Rng(0x2545_F491_4F6C_DD1D); + let mut splits = 0; for _ in 0..60 { let mut w = World::new(4096, &mut rng); for _ in 0..200 { @@ -1671,7 +2395,20 @@ fn revoking_every_untyped_empties_the_world() { // untyped가 삭제돼 버린 경우 그 밑의 오브젝트도 이미 종료됐어야 함 assert!(o.0 != 2 || boot.contains(o), "object {o:x?} survived the revocation of every untyped"); } + // 잘라낸 자식 untyped도 남지 않음. 남은 untyped는 부팅 때 받은 것뿐이고 + // 전부 비어 있음 + for &(b, n) in w.containers.values() { + for i in 1..n { + let s = unsafe { b.add(i) }; + if let Some(Entry { cap: Cap::Untyped { .. }, .. }) = unsafe { read(s) }.unwrap() { + assert_eq!(unsafe { (*s).depth }, 0, "a child untyped survived the revocation of every untyped"); + assert!(!unsafe { has_descendants(s) }); + } + } + } + splits += w.splits; } + assert!(splits > 50, "only {splits} splits happened before the revocations"); } // 자기 참조, 순환, 깊은 중첩: 케이퍼빌리티가 자기를 담은 컨테이너나 자기가 @@ -1682,30 +2419,22 @@ impl World { let root = node(ROOT_N); let memory = [r(0x4000_0000, granule * frames), r(0x5000_0000, granule * 4)]; unsafe { bootstrap(&cref(root, ROOT_N), &BOOT, &memory, &[]) }.unwrap(); - let mut w = World { - granule, - containers: BTreeMap::new(), - graveyard: Vec::new(), - objs: BTreeSet::new(), - torn: BTreeSet::new(), - finalized: 0, - ever: BTreeSet::new(), - reused: 0, - }; - w.containers.insert(BOOT.cnode, (root, ROOT_N)); - w.containers.insert(BOOT.tcb, (node(TCB_N), TCB_N)); - for i in 1..ROOT_N { - if let Some(e) = get(root, i) { - w.objs.insert(ident(&e.cap)); - } - } - w + World::adopt(granule, root) } fn root(&self) -> *mut Slot { self.containers[&BOOT.cnode].0 } + /// `step`과 같은 장부로 split하는 함수입니다. + fn cut(&mut self, ut: *mut Slot, dest: *mut Slot, granules: u64) { + unsafe { split(ut, dest, granules, self.granule) }.unwrap(); + let Some(Entry { cap: Cap::Untyped { base, size, .. }, .. }) = unsafe { read(dest) }.unwrap() else { + panic!("a split made no untyped") + }; + *self.uts.entry((base, size)).or_default() += 1; + } + /// `step`과 같은 장부로 retype하는 함수입니다. 새 오브젝트의 주소와, 컨테이너면 /// 그 슬롯 배열(아니면 null)을 돌려줍니다. fn make(&mut self, ut: *mut Slot, dest: *mut Slot, kind: ObjKind) -> (u64, *mut Slot) { @@ -1856,7 +2585,7 @@ fn an_untyped_parked_inside_a_cnode_carved_from_it() { revoke(c.add(7), &mut w).unwrap(); w.check(); assert!(!w.objs.contains(&(2, c_pa)) && !w.objs.contains(&(2, f_pa))); - assert!(!w.objs.contains(&(0, 0x4000_0000)), "the untyped cap was destroyed with its holder"); + assert!(!w.uts.contains_key(&(0x4000_0000, 16 * g)), "the untyped cap was destroyed with its holder"); } // 삭제로도 같고, CNode의 원본까지 자기 안에 있어도 같음 let mut w = World::with(g, 16); @@ -1955,6 +2684,7 @@ fn cnodes_nested_through_cnodes_with_tcbs_bound_across_levels() { fn random_sequences_with_self_reference_keep_every_invariant() { let mut finalized = 0; let mut selfs = 0; + let (mut splits, mut nested, mut child_objs, mut child_reused) = (0, 0, 0, 0); for seed in [0x9E37_79B9_7F4A_7C15u64, 0xD1B5_4A32_D192_ED03, 0x1234_5678_9ABC_DEF1, 0x0F0F_1E1E_2D2D_3C3C] { let mut rng = Rng(seed); for round in 0..250 { @@ -2001,9 +2731,17 @@ fn random_sequences_with_self_reference_keep_every_invariant() { w.check(); } finalized += w.finalized; + splits += w.splits; + nested += w.nested; + child_objs += w.child_objs; + child_reused += w.child_reused; } } assert!(finalized > 5_000, "only {finalized} finalized"); + assert!(splits > 600, "only {splits} splits succeeded"); + assert!(nested > 90, "only {nested} splits cut a child again"); + assert!(child_objs > 700, "only {child_objs} objects came from a child untyped"); + assert!(child_reused > 150, "only {child_reused} retypes reused a child's memory"); assert!(selfs > 300, "only {selfs} self-parking moves happened"); } diff --git a/design/en/README.md b/design/en/README.md index d2ad422..99e1af6 100644 --- a/design/en/README.md +++ b/design/en/README.md @@ -18,15 +18,15 @@ Read them in the order of the following table the first time. This order follows | [boot.md](boot.md) | From the first instruction to the root task: core selection, the drop to EL1, the jump to the higher half, and the fixed initialization order | | [memory.md](memory.md) | Kernel page tables, the boot-time table pool, the table reserve and rollback, W^X, guard pages, and the boot-time translation checks | | [user-address-space.md](user-address-space.md) | `AddrSpace` objects and their registry, user permissions, `MAP` and `UNMAP` without the kernel allocating tables, and how mappings are cleaned up when capabilities are removed | -| [capabilities.md](capabilities.md) | Per-task CNodes, rights and badges, the derivation list, untyped memory, retype and its failure guarantees, revoke and delete, and what task isolation does and does not cover | +| [capabilities.md](capabilities.md) | Per-task CNodes, rights and badges, the derivation list, untyped memory, retype and its failure guarantees, splitting an untyped into a memory budget for a task, revoke and delete, and what task isolation does and does not cover | | [dtb.md](dtb.md) | The device tree as hostile input: what the parser reads, its limits, and how it is fuzzed | | [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, including the rule that a task switched in between two ticks is not cut by the first tick it meets. Fixed time partitions: domains and the table, windows, the tick clock, the guard and the hold, the control capability and its two system calls, what is tested and what is proved about a model, and the limits of the claim | +| [scheduling.md](scheduling.md) | TCBs and their bound CNode and address space, task creation and teardown, the call that tells whether a task ended, 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. Fixed time partitions: domains and the table, windows, the tick clock, the guard and the hold, the control capability and its two system calls, what is tested and what is proved about a model, and the limits of the claim | | [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 | +| [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, what happens to the key when the vault ends, 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, how the root task supervises the terminal and the vault and starts them again, the screen and command rules, tests, and known gaps | Every note ends with a "**Known gaps**" section. The open security advisories are listed in [SECURITY.md](../../SECURITY.md). diff --git a/design/en/capabilities.md b/design/en/capabilities.md index f0d9f0b..01591b1 100644 --- a/design/en/capabilities.md +++ b/design/en/capabilities.md @@ -11,6 +11,7 @@ This note describes K0's capability model as it exists on the current `main` bra - the slot format and per-task CNodes - how free memory becomes untyped capabilities at boot - how user space turns untyped memory into kernel objects with `RETYPE` +- how user space cuts a smaller untyped capability out of a larger one with `UNTYPED_SPLIT` - the derivation list, and what copying, moving, deleting and revoking do The related code is in the files of the following table. @@ -59,7 +60,7 @@ In the following table, each kind is listed with the time it is created and what | Kind | Created | Grants | | --- | --- | --- | -| `Untyped` | at boot | a range of physical memory that can be retyped | +| `Untyped` | at boot, and by `UNTYPED_SPLIT` from another untyped | a range of physical memory that can be retyped and split | | `Frame` | by `RETYPE`, and at boot for the root task image | one granule of memory that can be mapped into an address space | | `PageTable` | by `RETYPE` | one page table that can be installed in an address space | | `Tcb` | by `RETYPE`, and at boot for the root task | a task that can be configured and resumed | @@ -90,7 +91,7 @@ The receiver gets the badge of the sender's capability in `x1`. So it can tell i ### The original flag -The capability that `RETYPE` creates, or that boot creates, is the **original** capability of its object. There is exactly one per object, and a copy is never an original. An object is finalized when its original capability is removed (see "Finalization"). Capabilities placed in a TCB's embedded slots are also marked as bound to that task. +The capability that `RETYPE` creates, or that boot creates, is the **original** capability of its object. There is exactly one per object, and a copy is never an original. A child untyped that `UNTYPED_SPLIT` creates carries the flag as well. An object is finalized when its original capability is removed (see "Finalization"). Capabilities placed in a TCB's embedded slots are also marked as bound to that task. ## CNodes @@ -157,7 +158,7 @@ The page is a snapshot. Capabilities created later by `RETYPE` do not appear in Each untyped capability has a **watermark**: how much of it has been used, counted from its base. A retype rounds the watermark up to the granule, takes the next granule as the new object, and moves the watermark past it. The new capability is the object's original and is inserted into the derivation list as a **child of the untyped** capability. -As long as live children exist, the watermark only grows. So two live objects carved from the same untyped capability never overlap. An untyped capability cannot be split. +As long as live children exist, the watermark only grows. So two live objects carved from the same untyped capability never overlap. `UNTYPED_SPLIT` cuts a smaller untyped capability from the same watermark, and that child counts as a child of the untyped just as an object does (see [Untyped split](#untyped-split)). The checks run in the following order, and the order is the important part. @@ -189,6 +190,62 @@ No object needs further initialization. Memory goes back to its untyped capability when everything derived from it is gone. If the untyped has no descendants at the time of a `RETYPE`, no live object occupies its range, so the watermark restarts at the base. Typically a task calls `CAP_REVOKE` on the untyped, which finalizes every object cut from it, and then retypes the same memory again. The memory is zeroed again each time. +A child untyped is a descendant too. The range of an untyped does not restart while one of its children exists, even when no object is left. + +`CAP_REVOKE` and `CAP_DELETE` do not zero the memory they free. A granule is zeroed when `RETYPE` makes the next object of it. A granule that is never retyped again can still hold old contents, so a task that wants a freed range erased has to retype every granule of it (see [Revoke and delete of a child](#revoke-and-delete-of-a-child)). + +## Untyped split + +`UNTYPED_SPLIT(untyped, granules, dest)` is system call 19. It cuts a smaller untyped capability, the **child**, out of an untyped capability, the **parent**. A task that holds only the child can make objects from the child's range and from nothing else. That is how a task gets a memory budget. + +| Register | Content | +| --- | --- | +| `x0` | the slot of the parent, an untyped capability | +| `x1` | the size of the child in granules, at least 1 | +| `x2` | an empty slot that receives the child | + +Both slots are in the caller's CNode. `x3` to `x5` are not read. The result in `x0` is 0 or an error code. + +The child starts at the parent's watermark, rounded up to the granule, and is exactly `x1` granules long. The parent's watermark moves past it. If the parent has no descendants, its watermark restarts at the base first, as for `RETYPE`. The call changes the two slots and nothing else: it touches no memory, uses no kernel resource and runs in constant time. `RETYPE` zeroes the memory of the child later, granule by granule, when it makes objects of it. + +The child is an original capability. It goes into the derivation list right after its parent, one level deeper, and its own watermark starts at 0. The following rules hold for it: + +- **Exact size**: every object is one granule, so a child of n granules yields exactly n objects and then answers `EXHAUSTED`. The parent keeps the rest of its range. +- **No overlap**: the child lies below the parent's watermark, so the parent gives that range to nothing else while the child exists. Children and objects of one parent never overlap. +- **Split again**: a child can be split like any untyped. The objects that come from a child and from its own children together are still at most the child's granules. +- **No copy**: a child cannot be copied (`BAD_CAP`), like every untyped. One range therefore always has one watermark. +- **Move**: `CAP_MOVE` puts a child into another CNode, and its descendants stay under it in the derivation list. Moving a child into the CNode of another task gives that task its budget. The task that moved it can then no longer name it, and takes the memory back by revoking the parent. + +`RETYPE` did not change, and `bootinfo::VERSION` stays 5. The root task uses a child untyped as the slab of each service it supervises (see [terminal.md](terminal.md#supervision)). + +### Revoke and delete of a child + +- **CAP_REVOKE on a child**: it removes everything that was made from the child and keeps the child. The memory goes back to the child, not to the parent. The child has no descendants any more, so its next `RETYPE` or split starts at the child's base again. The parent's watermark does not change. +- **CAP_DELETE on a child**: it removes the child and everything that was made from it. The parent does not get the range back at that moment. The parent restarts at its base only when it has no descendants at all, which is the rule of [Memory reuse](#memory-reuse). +- **CAP_REVOKE on the parent**: it removes the children, their children and every object made from any of them, in one call. +- **A child that lies inside what it built**: if the slot of the revoked child lies in a CNode that the same revoke finalizes, the child is deleted as well. This is the case when a child was moved into the CNode of a task and that CNode was made from the same child. Every slot of a finalized CNode is emptied, whatever it holds. +- **Erasing a child**: a revoke does not erase the range. To erase the whole range of a revoked child, a task retypes every granule of it and holds all the new capabilities until the last one is made. If it made and deleted one object at a time, the child would have no descendants after each delete and would hand out its first granule again and again. + +A child bounds memory, and with it the number of objects its holder can have at one time. It does not bound time. The kernel is still not preemptible, and `CAP_REVOKE` and `CAP_DELETE` still take time in proportion to the number of capabilities they remove. Copies count in that number, so the size of the child alone does not limit it. A revoke that can be interrupted and continued does not exist. + +> [!NOTE] +> A child untyped is a budget of memory, not of time. `CAP_REVOKE` and `CAP_DELETE` on it are as long as the number of capabilities they remove, and the kernel is not preemptible. + +### Errors of UNTYPED_SPLIT + +The checks run in the order of the following table. A refused call changes nothing. + +| Code | Cause | +| --- | --- | +| `BAD_SIZE` (-27) | `x1` is 0. This is checked before the slots are looked at | +| `BAD_SLOT` | the parent or the destination slot number is 0 or out of range | +| `NOT_UNTYPED` | the parent slot is empty or holds another kind of capability | +| `OCCUPIED` | the destination slot holds a capability. This includes the parent's own slot | +| `EXHAUSTED` | the parent has not enough room left, the size overflows, or the last granule of the child could not be the address of an object | +| `TOO_DEEP` | the child would exceed the depth limit `MAX_DEPTH` | + +The call cannot fail with `KERNEL_RESOURCE`, because it uses no kernel table. + ## The derivation list All capabilities are linked into one doubly linked list in preorder, and every slot stores its depth. The descendants of a slot are the slots that follow it directly with a greater depth, so finding them needs no tree and no allocation. The following figure shows how the list grows from a boot capability through `RETYPE` and `CAP_COPY`, and what `CAP_REVOKE` and `CAP_DELETE` do. @@ -201,10 +258,11 @@ Each operation changes the list as follows: - **Boot capability**: a root (depth 0) of its own list. - **RETYPE**: inserts the new capability right after the untyped, one level deeper. +- **UNTYPED_SPLIT**: inserts the child untyped right after its parent, one level deeper. - **CAP_COPY**: inserts the copy right after its source, one level deeper. **Copies are children of their source**. That is what makes "revoke the parent" remove the copies, and it is the reason a copy can never outlive the capability it was made from. - **CAP_MOVE**: keeps the position in the list, the depth, the flags and the mapping record. -The depth is capped at `MAX_DEPTH`. A `CAP_COPY` or `RETYPE` that would exceed it fails with `TOO_DEEP`, so the depth counter cannot overflow. Every list operation checks that the neighbours point back at the slot. If a link is broken the operation changes nothing and the kernel halts with `k0: FATAL cap derivation list corrupt`. +The depth is capped at `MAX_DEPTH`. A `CAP_COPY`, `RETYPE` or `UNTYPED_SPLIT` that would exceed it fails with `TOO_DEEP`, so the depth counter cannot overflow. Every list operation checks that the neighbours point back at the slot. If a link is broken the operation changes nothing and the kernel halts with `k0: FATAL cap derivation list corrupt`. ## Copy, move, delete and revoke @@ -226,7 +284,7 @@ These two are stricter than seL4 on purpose. In seL4, deleting a capability does > [!WARNING] > In K0, deleting any capability deletes everything derived from it. A copy never outlives its source, and an object dies with its original capability. -Revoking an untyped finalizes everything cut from it. Within one revoke of an ancestor, an object's original may be removed before its copies, so a finalization callback must tolerate callbacks for copies of an object that is already finalized. All of them are gone before the system call returns. +Revoking an untyped finalizes everything cut from it and removes its child untyped capabilities with everything made from them (see [Revoke and delete of a child](#revoke-and-delete-of-a-child)). Within one revoke of an ancestor, an object's original may be removed before its copies, so a finalization callback must tolerate callbacks for copies of an object that is already finalized. All of them are gone before the system call returns. ## Finalization and the pending list @@ -255,10 +313,12 @@ The following table lists the capabilities and rights each system call requires. | `DEBUG_PUTC` | a `Console` with `W` | | `CONSOLE_READ` | a `Console` with `R` (only in images built with `console-input`) | | `RETYPE` | an `Untyped`, and a free destination slot in the caller's CNode | +| `UNTYPED_SPLIT` | an `Untyped`, and a free destination slot in the caller's CNode | | `MAP` | a `Frame` whose rights cover the permission (`RO` needs `R`, `RW` needs `R\|W`, `RX` needs `R\|X`) or a `PageTable`, and an `AddrSpace` naming the target | | `UNMAP` | a `Frame` or `PageTable` that is mapped | | `TCB_CONFIGURE` | a `Tcb` in the `Inactive` state, an `AddrSpace` and a `CNode` | | `TCB_RESUME` | a `Tcb` in the `Stopped` state | +| `TCB_STATUS` | a `Tcb`, in any state (see [scheduling.md](scheduling.md#asking-whether-a-task-ended)) | | `PART_SET_TABLE` | the `PartCtl` | | `PART_SET_DOMAIN` | the `PartCtl`, and a `Tcb` in the `Stopped` state | | `SEND`, `CALL` | an `Endpoint` with `W` | @@ -282,7 +342,8 @@ The following table lists the error codes for slot problems and their meaning. | --- | --- | | `BAD_SLOT` | the slot number is 0, out of range, or the slot is empty (also when the task has no CNode bound) | | `BAD_CAP` | the slot holds a capability of the wrong kind, or one that cannot be copied or moved | -| `NOT_UNTYPED` | `RETYPE` source is not an untyped | +| `NOT_UNTYPED` | the source of `RETYPE` or `UNTYPED_SPLIT` is not an untyped | +| `BAD_SIZE` (-27) | the granule count of `UNTYPED_SPLIT` is 0 | | `OCCUPIED` | the destination slot is not empty (this replaces the old `OUT_OF_SLOTS`, still -4) | | `NO_RIGHTS` | the capability lacks the right the call needs, or a copy mask leaves no rights | | `BAD_PERM` | the mapping permission or the rights mask is not valid | @@ -310,15 +371,31 @@ The following table lists the error codes for slot problems and their meaning. - that a pair copy is all-or-nothing - that depth is bounded - that broken links stop the operation -- **Model tests**: `random_operation_sequences_keep_every_invariant` runs random sequences of retype, copy, move, pair-bind, delete and revoke over both granules (160 worlds of 260 steps). After every step, it checks the following: +- **Host unit tests of the split**: 17 of the 71 tests of `k0-cap` are about `UNTYPED_SPLIT`. They check the following: + - that the child starts on a granule boundary at the parent's watermark, and that the parent's watermark moves past it + - that every refused split leaves both slots as they were, including sizes that overflow and a range near the top of the address space + - that a child whose last granule could not be the address of an object is not made + - that a child yields exactly its granules and the parent keeps the rest + - that children and objects of one parent never overlap + - that revoking a child restarts the child and not the parent + - that deleting a child gives nothing back until the parent has no descendants + - that a child cannot be copied, and that it moves with everything under it + - that revoking an ancestor removes nested children and their objects + - that the depth of a split is bounded + - that a slab is used again in place after a revoke, round after round (`the_supervisor_recipe_reuses_the_slab_in_place`) + - that a child whose slot lies in a CNode made from it is deleted by its own revoke, and that the same revoke deletes the parent when the parent's slot lies there + - that the removal of a child untyped is reported once, as an original + - that erasing a revoked child needs all its granules held +- **Model tests**: `random_operation_sequences_keep_every_invariant` runs random sequences of retype, split, copy, move, pair-bind, delete and revoke over both granules (160 worlds of 260 steps). After every step, it checks the following: - that the list is a valid preorder - that every live object has exactly one original - that no capability names a finalized object - that destroyed slot arrays are empty - that retype never hands out a live object's memory + - that a child untyped consists of whole granules, and that the children of one untyped do not overlap - It also asserts that the run exercised enough finalizations, task teardowns and memory reuse. A second test (`revoking_every_untyped_empties_the_world`) revokes every untyped capability after random activity and checks that no retyped object survives. -- **Destruction tests**: they run a very deep derivation chain and deeply nested CNodes on a small fixed stack, to show that destruction is iterative. + It also asserts that the run exercised enough finalizations, task teardowns and memory reuse, and enough splits, splits of a child, objects made from a child and reuse of a child's range. A second test (`revoking_every_untyped_empties_the_world`) revokes every untyped capability after random activity and checks that no retyped object and no child untyped survives. +- **Destruction tests**: they run a very deep derivation chain, deeply nested CNodes and a chain of 60,000 nested child untyped capabilities on a small fixed stack, to show that destruction is iterative. - **Boot self-tests**: the root task builds confined tasks, each with its own CNode and its own address space that maps only the image text and read-only data. Among other things, the tests check the following: - that slot numbers of the root task mean nothing in the confined CNode - that a read of a root-only address faults at exactly that address @@ -331,6 +408,16 @@ The following table lists the error codes for slot problems and their meaning. - that revoked untyped memory is retyped again (to exhaustion, three rounds, zeroed each time) The markers are listed in `tools/qemu-boot-test.sh`. The script also requires an exact number of `k0: task fault` lines and exactly one `k0: unknown syscall` line. So a task that is resumed after it was destroyed, or that dies for the wrong reason, fails the test. +- **Split self-test**: `test_split` in `userspace/root-task/src/main.rs` runs in every image and prints `root: untyped split tests pass`, after `root: timeout tests pass` and before `root: revocation tests pass`. It checks the following: + - that each refusal returns its error code and leaves no capability in the destination slot + - that a child can be neither copied nor mapped + - that a task built from a slab of 24 granules, with a budget of 8 granules that was split off the slab and moved into its CNode, gets exactly 8 objects from that budget. The task also checks from inside that revoking its budget gives the memory back to the budget, and that it can give the whole budget to a child and split that child again + - that the rest of the slab stays usable for the root task while the task uses up its budget + - that revoking the slab removes the task, its CNode, its address space and the budget in one call + - that the slab then yields exactly 24 frames again. Four of them are mapped and read over the whole granule and must be zero: the ones that held a last-level page table, the task's stack, the TCB and a frame the root task had written + - that after the slab is deleted the parent still makes objects + + The task and the revoke run twice on the same slab, so the second round shows that the same memory and the same slots can be used again. The 16 KiB image boots and passes the boot checks on QEMU `-cpu max`, and it boots under HVF on Apple cores. The default 4 KiB image passes the boot matrix in CI. @@ -339,15 +426,17 @@ The 16 KiB image boots and passes the boot checks on QEMU `-cpu max`, and it boo > [!NOTE] > Capability transfer does not exist yet. Capabilities cannot be sent over IPC, and tasks get capabilities only by `CAP_COPY` and `CAP_MOVE` into a CNode they already hold. Notifications and fault delivery to a handler task are not in the model yet, and there is one core. Timeouts exist (see [ipc.md](ipc.md)). -- **Availability**: it is not isolated. The kernel no longer halts when every task is blocked, a task can bound its own waits with timeouts, and the kernel page tables and the address space registry can no longer be used up. A task that waits without a timeout can still wait forever if its partner never acts, so a server must give a timeout on every wait. There is no priority and no CPU budget, and a task that holds untyped memory can create many tasks and dilute the share of the others. The kernel is not preemptible, so a long system call such as `CAP_REVOKE` delays everybody. See GHSA-q99x-2wrv-358p in [SECURITY.md](../../SECURITY.md) for the state of the advisory. +- **Availability**: it is not isolated. The kernel no longer halts when every task is blocked, a task can bound its own waits with timeouts, and the kernel page tables and the address space registry can no longer be used up. A task that waits without a timeout can still wait forever if its partner never acts, so a server must give a timeout on every wait. There is no priority and no CPU budget, and a task that holds untyped memory can create many tasks and dilute the share of the others. A child untyped limits how much memory such a task has, and so how many objects it can make, but nothing more. The kernel is not preemptible, so a long system call such as `CAP_REVOKE` delays everybody. See GHSA-q99x-2wrv-358p in [SECURITY.md](../../SECURITY.md) for the state of the advisory. - **A queued sender**: a sender already queued on an endpoint still delivers its message once more after its capability is revoked. - **Differences from seL4**: they are the following: - Single-level CSpace (no guards, no multi-level lookup). - Deleting a capability also deletes everything derived from it. An object dies with its original capability. - - All objects are exactly one granule, and an untyped cannot be split. + - All objects are exactly one granule. A smaller untyped is cut by a separate call, `UNTYPED_SPLIT`, with a size in whole granules, and not by `RETYPE`. - No capability transfer over IPC. - No hardware ASIDs: TTBR0 changes flush the whole TLB, as does every unmap, table detach and address space destruction. - **Control capabilities**: they are all or nothing. `Tcb`, `CNode` and `AddrSpace` capabilities carry no rights, so there is no reduced copy of one. Whoever holds such a capability has full control of the object, and a task is controlled by whoever holds a capability to its TCB, its CNode or its address space. `PartCtl` is all or nothing as well: one capability covers the table and the domains of all tasks, and it cannot be split into a part that sets the table and a part that places tasks. - **New code after boot**: it cannot be loaded. Because of W^X by capability rights, executable memory exists only in the root task image. -- **Interrupts during revoke**: they are masked. The time of `CAP_REVOKE` and `CAP_DELETE` is proportional to the number of capabilities removed. +- **Interrupts during revoke**: they are masked. The time of `CAP_REVOKE` and `CAP_DELETE` is proportional to the number of capabilities removed. `UNTYPED_SPLIT` does not change this: a child untyped bounds memory, not the time of a revoke, and a revoke that can be interrupted and continued does not exist. +- **A child untyped is fixed**: it cannot be grown, shrunk or merged back into its parent. The parent gets the range of a deleted child back only when nothing derived from the parent is left. +- **Revoke does not erase**: memory freed by `CAP_REVOKE` or `CAP_DELETE` is not zeroed until `RETYPE` makes an object of it again. A task that needs a freed range erased has to retype every granule of it. - **Not verified here**: anything in tier 3: any real board, KVM, Firecracker, Cloud Hypervisor, crosvm, the 16550 console driver (never run), GICs with real security extensions on hardware, and CPUs with `HCR_EL2.E2H` fixed to 1 (that path follows Linux and has not run anywhere). Tier 1 (`tools/boot-matrix.sh`, run in CI and locally) and tier 2 (by hand on 2026-11-11 and 2026-11-12, Apple M5 Pro, QEMU HVF) are the supported set. The UEFI rows are listed in [uefi.md](uefi.md). diff --git a/design/en/exceptions.md b/design/en/exceptions.md index 158efe7..9ffb59a 100644 --- a/design/en/exceptions.md +++ b/design/en/exceptions.md @@ -105,6 +105,10 @@ The system call number is in `x8`. Arguments are in `x0` to `x5`, and the result | 16 | `CONSOLE_READ` | read one byte of console input (only in an image built with `console-input`, see below); needs a `Console` capability with the read right | | 17 | `PART_SET_TABLE` | set the time partition table; needs the `PartCtl` capability (see [scheduling.md](scheduling.md#the-control-capability-and-the-two-system-calls)) | | 18 | `PART_SET_DOMAIN` | put a task that has not run yet in a time partition domain; needs the `PartCtl` capability | +| 19 | `UNTYPED_SPLIT` | cut a smaller untyped capability of a given number of granules out of an untyped capability, into a destination slot the caller names (see [capabilities.md](capabilities.md#untyped-split)) | +| 20 | `TCB_STATUS` | ask whether a task has not started, is alive or has ended; needs a `Tcb` capability and changes nothing (see [scheduling.md](scheduling.md#asking-whether-a-task-ended)) | + +`TCB_STATUS` is the only call whose successful result in `x0` is not always 0: it returns 0, 1 or 2 for the three answers, and a negative value is still an error. > [!IMPORTANT] > An unknown number is not just an error code. K0 treats it as a sign that the task is broken or hostile, prints `k0: unknown syscall N, killing task`, and terminates the caller. @@ -121,6 +125,8 @@ k0: task fault dabort-lower (esr 0x92000046 elr 0x400398 far 0x0), killing task It then calls `kill_current`, which runs the teardown described in [scheduling.md](scheduling.md#teardown). It removes the task from whatever queue it is in, cuts the reply links in both directions and marks the task `Dead`. Because the reply links are cut, the task waiting for this task's reply wakes with `NO_REPLY` (see [ipc.md](ipc.md)). `EXIT` and an unknown system call use the same path. +Nothing is sent to another task when a task ends this way. A task that holds the `Tcb` capability of the dead task can ask with `TCB_STATUS` and gets `ENDED`, without a reason (see [scheduling.md](scheduling.md#asking-whether-a-task-ended)). + ### The finish path Every system call and every fault ends in `finish`, which runs after the handler and after all capability cleanup. A handler can kill the calling task without a fault: `EXIT`, deleting its own CNode, address space or TCB, or revoking the untyped it came from. So `finish` decides what happens to the context only once everything else is done: @@ -137,7 +143,7 @@ When the running domain has no ready task (for example its last runnable task di | `k0: idle (waiting for a timeout)` | the first time the kernel idles while at least one waiter has a deadline | | `k0: all tasks stopped (none ready, no timeout pending)` | the first time the kernel idles while no waiter has a deadline | -In the second state nothing can wake a task today, because there are no notification objects and no device interrupts for tasks other than console input. The machine stays idle. In an image with `console-input`, a task that waits for console input counts as a waiter: when that is the only thing left to wait for, the kernel prints nothing, which is the normal state of a terminal image. The second line is printed only when there is neither a timed waiter nor a console waiter. While a table that names a domain other than the root domain is set or pending, the first line is not printed, and the second is printed only when no domain has a ready task or a timed waiter and no task waits for console input. `tools/qemu-boot-test.sh` treats any line that starts with `k0: all tasks` as a failure. +In the second state nothing can wake a task today, because there are no notification objects and no device interrupts for tasks other than console input. The machine stays idle. In an image with `console-input`, a task that waits for console input counts as a waiter: when that is the only thing left to wait for, the kernel prints nothing. A terminal image in service also has a timed waiter, the root task between two polls of its supervisor, and the first line was already printed once during the self-tests, so it prints nothing either. The second line is printed only when there is neither a timed waiter nor a console waiter. While a table that names a domain other than the root domain is set or pending, the first line is not printed, and the second is printed only when no domain has a ready task or a timed waiter and no task waits for console input. `tools/qemu-boot-test.sh` treats any line that starts with `k0: all tasks` as a failure. ### The exit check @@ -179,7 +185,7 @@ The test also requires the ordered markers, among them `k0: task fault dabort-lo ## Known gaps > [!NOTE] -> A faulting task is always killed. Delivering the fault to a handler task over IPC, so that a pager or supervisor can respond, is planned but does not exist yet. +> A faulting task is always killed. Delivering the fault to a handler task over IPC, so that a pager or supervisor can respond, is planned but does not exist yet. What exists is `TCB_STATUS`: a holder of the task's `Tcb` capability can ask whether the task ended, and learns neither when nor why. - Any exception at EL1 other than an interrupt is **fatal**. The kernel does not recover from its own faults: the fatal vector path prints a diagnosis and halts the whole system. A kernel invariant violation found by the kernel's own checks stops the system the same way through `k0_arch::fatal`. - A task that faults or makes an unknown system call kills only itself. If no task is ready afterwards, the kernel idles instead of stopping (see [The finish path](#the-finish-path)). A task that waits without a timeout can still wait forever if its partner never acts, and the scheduler has no priority and no CPU budget (GHSA-q99x-2wrv-358p is still listed as affecting 0.1.0 and earlier). Isolation does not cover availability. diff --git a/design/en/ipc.md b/design/en/ipc.md index 90f849a..94836ed 100644 --- a/design/en/ipc.md +++ b/design/en/ipc.md @@ -159,7 +159,7 @@ If no task of the same domain is ready at that point, the kernel does not stop. - `k0: idle (waiting for a timeout)`: at least one waiter has a deadline, so something will wake a task. - `k0: all tasks stopped (none ready, no timeout pending)`: no waiter has a deadline and no task waits for console input. Nothing can wake a task in that state today, because K0 has no notification objects and the only device interrupt that wakes a task is console input, so the machine stays idle. `tools/qemu-boot-test.sh` treats any line that starts with `k0: all tasks` as a failure. -When the only thing left to wait for is console input, the kernel prints neither line. That is the normal state of a terminal image. While a time partition table that names a domain other than the root domain is set or pending, the first line is not printed at all, and the second only when no domain has a ready task or a timed waiter and nobody waits for input (see [scheduling.md](scheduling.md#when-there-is-nothing-left-to-run)). +When the only thing left to wait for is console input, the kernel prints neither line. A terminal image in service prints neither as well: its root task waits with a timeout between two polls of the supervisor, and the first line was already printed once during the self-tests (see [terminal.md](terminal.md#supervision)). While a time partition table that names a domain other than the root domain is set or pending, the first line is not printed at all, and the second only when no domain has a ready task or a timed waiter and nobody waits for input (see [scheduling.md](scheduling.md#when-there-is-nothing-left-to-run)). > [!WARNING] > The kernel no longer halts when every task is blocked, and a task can bound its own waits with timeouts. Availability is still not protected. A task that waits without a timeout can wait forever if its partner never acts, and a confined task that holds a capability to an endpoint can still make others wait. This is the subject of advisory GHSA-q99x-2wrv-358p in [SECURITY.md](../../SECURITY.md). The advisory is updated at release time. diff --git a/design/en/scheduling.md b/design/en/scheduling.md index 1d4d5bd..00bf012 100644 --- a/design/en/scheduling.md +++ b/design/en/scheduling.md @@ -21,7 +21,7 @@ The code is in the following places: - `crates/k0-sched/src/lib.rs` (the queues and the installed task, around `Core`) - the timer in `crates/k0-arch/src/irq.rs` - `teardown` in `crates/k0-ipc/src/lib.rs` -- `sys_tcb_configure`, `sys_tcb_resume`, `sys_part_set_table`, `sys_part_set_domain`, `k0_preempt`, `k0_leave`, `wait_for_work`, `kill_current` and `finish` in `kernel/src/syscall.rs` +- `sys_tcb_configure`, `sys_tcb_resume`, `sys_tcb_status`, `sys_part_set_table`, `sys_part_set_domain`, `k0_preempt`, `k0_leave`, `wait_for_work`, `kill_current` and `finish` in `kernel/src/syscall.rs` The note describes the current `main` branch (unreleased). @@ -319,6 +319,33 @@ The running task is the one case teardown does not finish. The system call handl A dead task's frame is not freed by teardown. It stays a `Dead` TCB, and `TCB_CONFIGURE` and `TCB_RESUME` refuse it, so a dead task is never restarted. The memory is reusable once the TCB's original capability is deleted, or the untyped it came from is revoked, and the untyped is then retyped, which zeroes the frame again. A task that merely exited keeps its two bound capabilities until then. +## Asking whether a task ended + +`TCB_STATUS` is system call 20. It tells the holder of a `Tcb` capability whether the task has been started and whether it has ended. `x0` is the slot of the `Tcb` capability in the caller's CNode. The result comes back in `x0`, and it follows from the task's state alone, as in the following table. + +| Result | Value | Task state | +| --- | --- | --- | +| `NOT_STARTED` | 0 | `Inactive` or `Stopped`: not configured, or configured and never resumed | +| `ALIVE` | 1 | `Ready`, `Running`, or any of the blocked states (`BlockedSend`, `BlockedRecv`, `BlockedCall`, `BlockedReply`, `BlockedConsole`) | +| `ENDED` | 2 | `Dead`: the task exited, faulted, made an unknown system call or was torn down | + +A negative result is an error. `BAD_SLOT` means that the slot number is 0, out of range, or that the slot is empty. `BAD_CAP` means that the slot holds another kind of capability. Every other system call returns 0 on success, so this is the only one whose successful result in `x0` can be something else. The values are in the module `tcb_status` of `crates/k0-abi/src/lib.rs`. + +The call has the following properties: + +- **It changes nothing**: it reads the state field of the TCB and writes nothing. A call that succeeds and a call that is refused both leave the slots, the TCB, the queues and the scheduler as they were. +- **No reason**: it does not say why a task ended. The exit code and the way a task ends are chosen by that task, so the kernel does not offer them as a basis for a decision. It does not tell the blocked states apart either. +- **A task that never ran**: a task that was torn down before it first ran is `ENDED` as well. +- **The answer is final**: `Dead` is a final state, because teardown returns at once on a `Dead` task, `TCB_CONFIGURE` takes only `Inactive` and `TCB_RESUME` takes only `Stopped`. A holder that asks from time to time therefore cannot miss the end of a task. The answer stays `ENDED` while the `Tcb` capability exists. Once that capability is deleted, the slot is empty and the answer is `BAD_SLOT`. +- **Who may ask**: `Tcb` capabilities carry no rights, so every holder of one may ask. A task may ask about itself and gets `ALIVE`. +- **Only when asked**: the kernel sends nothing when a task ends. There is no notification, and a fault is not delivered to a handler task (see [exceptions.md](exceptions.md)). A holder that wants to know has to ask, and ask again. +- **In every image**: the call needs no feature. + +> [!NOTE] +> The kernel tells nobody by itself that a task ended. A holder of the `Tcb` capability has to ask, and it learns neither the reason nor anything about a task that hangs without ending. + +The root task of a terminal image uses this call to supervise the terminal and the vault (see [terminal.md](terminal.md#supervision)). + ## When there is nothing left to run The kernel no longer parks the core when no task can run. `wait_for_work` in `kernel/src/syscall.rs` takes over in three cases: the current task blocked and its domain has no ready task, the current task died and its domain has no ready task, and a tick cut the running task at the end of its window and the incoming domain has no ready task. In the third case the cut task is parked `Ready` in its own queue, and nothing returns to EL0 until the scheduler installs a task. The loop works as follows: @@ -332,7 +359,7 @@ Timer ticks keep being counted and handled while the kernel waits. Unless a tabl - `k0: idle (waiting for a timeout)`: at least one waiter has a deadline. - `k0: all tasks stopped (none ready, no timeout pending)`: no waiter has a deadline and no task waits for console input. Nothing can wake a task in that state today, because there are no notification objects and no device interrupts for tasks other than console input, so the machine stays idle. -When the only thing left to wait for is console input (an image with `console-input`), the kernel prints nothing: that is the normal state of a terminal image. +When the only thing left to wait for is console input (an image with `console-input`), the kernel prints nothing. A terminal image in service is quiet for another reason: its root task waits with a timeout between two polls of the supervisor (see [terminal.md](terminal.md#supervision)), so there is a timed waiter, and the first line was already printed once during the self-tests. While a table that names a domain other than the root domain is set or pending, waiting in an empty window is normal, so the first line is not printed. The second line is still printed, once, when no domain has a ready task, no domain has a timed waiter and no task waits for console input. A ready task of a domain that no table names counts as ready in this check, although it will never run. @@ -347,13 +374,14 @@ The system call paths and the kernel side of the scheduler (`k0-sched`, `k0-ipc` - 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, +- ask `TCB_STATUS` about a task in each state it can show (see [The status test at boot](#the-status-test-at-boot)), - 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, - run the partition test (`userspace/root-task/src/partition.rs`, see [The partition test at boot](#the-partition-test-at-boot)), - 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: slice test yield pass`, `root: slice test block pass`, `root: preempt test pass`, `root: partition refusal pass`, `root: partition window pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: revocation tests pass`, `root: partition sealed` 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: tcb status tests pass`, `root: slice test yield pass`, `root: slice test block pass`, `root: preempt test pass`, `root: partition refusal pass`, `root: partition window pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: revocation tests pass`, `root: partition sealed` 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. @@ -368,6 +396,16 @@ This is a search in a bounded model (up to 6 tasks), **not a proof**. Each of ni With the slice rule 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. +### The status test at boot + +`sys_tcb_status` is in the kernel binary, which has no host tests. A host test of `k0-abi` checks only that the three result values are distinct and never negative. The call itself is checked by the root task at every boot. The checks sit where the other self-tests already have a task in the state in question, and the line `root: tcb status tests pass` follows `root: fault isolation tests pass`. Some of the checks run in later tests. They cover the following: + +- **Refusals**: slot 0, a slot number out of range and an empty slot give `BAD_SLOT`. A `Console` capability and a `Frame` capability give `BAD_CAP`. +- **Not started**: a TCB that was never configured, the same TCB after a refused `TCB_CONFIGURE`, and a TCB that is configured and not yet resumed. +- **Alive**: the root task itself, a task right after `TCB_RESUME`, a task that waits in `RECV` and a task that waits for a reply. +- **Ended**: a task after `EXIT` (asked twice, with the same answer), a server that exited, a task after a data abort, after an FP/SIMD trap and after an unknown system call, a task whose CNode was revoked, a task whose address space was deleted, and a task that was torn down before it ever ran. +- **Deleted**: after `CAP_DELETE` of the `Tcb` capability the answer is `BAD_SLOT`. + ### Host tests of the partition scheduler The crate `k0-part` has 36 host tests, run by `tools/host-test.sh`. @@ -384,7 +422,7 @@ The crate `k0-part` has 36 host tests, run by `tools/host-test.sh`. - **The clock arithmetic** (9 tests): the tick number against a separately written reference, the instants just before and at the armed instant, values near the end of the counter range, a period of zero, and that the tick number never goes back or repeats. - **The recorded results of the Lean model** (3 tests): see [What is proved](#what-is-proved). -`k0-cap` has 54 host tests. Two of them are about `PartCtl`: no copy of it can be made whatever the mask and the badge, and a `PartCtl` word that carries anything else does not decode. +`k0-cap` has 71 host tests. Two of them are about `PartCtl`: no copy of it can be made whatever the mask and the badge, and a `PartCtl` word that carries anything else does not decode. `k0-sched`, `k0-ipc` and the kernel binary have no host tests. What they add to `Core` (the queues, the timed lists, the calls into the timer) is covered by the boot test and by review. @@ -438,4 +476,5 @@ The link between the model and the code is a test, not a proof. The host test `c - **Blocked tasks**: a blocked task wakes when its IPC partner acts, when its deadline passes, or when the endpoint is deleted. - **Dead TCB**: it is not reclaimed by teardown. Its frame becomes reusable only when its capability is deleted or its untyped is revoked and retyped. - **Address space identifiers**: there are no hardware address space identifiers, so every switch between address spaces flushes the whole TLB. -- **Dead task**: it cannot be restarted. A new task needs a new TCB. +- **Dead task**: it cannot be restarted. A new task needs a new TCB. The supervisor of a terminal image does exactly that: it removes what is left of an ended service and builds a new task in the same memory and the same slots (see [terminal.md](terminal.md#supervision)). +- **No notice when a task ends**: the kernel tells no task that another task ended. The holder of the `Tcb` capability can ask with `TCB_STATUS`, so a supervisor has to poll. It learns no reason, and a task that hangs without ending looks `ALIVE`. diff --git a/design/en/terminal.md b/design/en/terminal.md index cb8e505..f9b36fb 100644 --- a/design/en/terminal.md +++ b/design/en/terminal.md @@ -6,7 +6,7 @@ English | [한국어](../kr/terminal_KR.md) -This note describes how a person can talk to K0 over the serial line. The kernel receives bytes from the console UART and hands them to one task, the **terminal**, with the system call `CONSOLE_READ`. The terminal is the operator of the vault (see [vault.md](vault.md)): it shows the vault's state, makes the key and erases it. The code is in `crates/k0-conin` (the receive logic), `kernel/src/syscall.rs` (`CONSOLE_READ`), `userspace/k0-term` (the terminal) and `userspace/root-task/src/service.rs` (wiring and the check). +This note describes how a person can talk to K0 over the serial line. The kernel receives bytes from the console UART and hands them to one task, the **terminal**, with the system call `CONSOLE_READ`. The terminal is the operator of the vault (see [vault.md](vault.md)): it shows the vault's state, makes the key and erases it. The code is in `crates/k0-conin` (the receive logic), `kernel/src/syscall.rs` (`CONSOLE_READ`), `userspace/k0-term` (the terminal), `userspace/k0-sup` (the policy that supervises the terminal and the vault) and `userspace/root-task/src/service.rs` (wiring, the check and the supervisor's loop). > [!NOTE] > Input and the terminal are optional and off by default. An image built without `console-input` has no receive code, no `CONSOLE_READ` and none of the log lines in this note. An image built without `terminal` has no terminal code. @@ -83,17 +83,20 @@ Only one task can wait for input at a time. A second reader gets `BUSY` (-23). A - **Only in the reader's window**: under a time partition table the byte is handed over only while the reader's domain runs. Otherwise it waits in the ring until the next tick at which that domain runs (see [scheduling.md](scheduling.md#console-input-under-a-table)). A terminal image runs with one domain, so this does not apply to it today. - **Waking on a capability change**: a waiter whose capability is deleted, revoked or moved wakes at once with `REVOKED`. - **Waking on a timeout**: a reader that gave a timeout in its flags is woken when it runs out (see [scheduling.md](scheduling.md) for timeouts). -- **Quiet idle**: when the only thing left to wait for is console input, the kernel prints nothing. That is the normal state of a terminal image. `k0: all tasks stopped (none ready, no timeout pending)` is printed only when there is neither a timed waiter nor a console waiter. +- **Quiet idle**: when the only thing left to wait for is console input, the kernel prints nothing. `k0: all tasks stopped (none ready, no timeout pending)` is printed only when there is neither a timed waiter nor a console waiter. A terminal image in service has both: the terminal waits for input, and the root task waits with a timeout between two polls of the supervisor (see [Supervision](#supervision)). ## The terminal's wiring and the hostile-task check A terminal image runs all self-tests first. Then the root task does the following: -1. It starts a new vault (if one is built in) and hands it the boot seed. The log line is `root: vault seeded`, or `root: vault has no seed (boot seed has no entropy)`, or `root: vault has no seed (no algorithm in this image)`. -2. It runs two hostile tasks wired exactly like the terminal. They must be refused and must end in a fault. The lines are `root: terminal console filter [...]`, `root: terminal wiring holds` and two `k0: task fault` lines. -3. It drops its own admin capability, starts the terminal and blocks for ever. The line is `root: service started`, then the banner follows. +1. It cuts one slab of memory for each service out of an untyped capability and, if a vault is built in, makes the objects that both services share (see [Supervision](#supervision)). +2. If a vault is built in, it tries the restart path of the vault on a vault that never gets a seed. The line is `root: vault restart test pass`. +3. It starts a new vault (if one is built in) and hands it the boot seed. The log line is `root: vault seeded`, or `root: vault has no seed (boot seed has no entropy)`, or `root: vault has no seed (no algorithm in this image)`. +4. It runs two hostile tasks wired exactly like the terminal, one after the other, in the place where the terminal will run. They must be refused and must end in a fault, and after each one the supervisor's code takes back everything the task was made of. The lines are `root: terminal console filter [...]`, `root: terminal wiring holds`, two `k0: task fault` lines and `root: terminal restart test pass`. +5. It checks that the vault is alive and in the same state as before the hostile tasks, and drops its own admin capability. +6. It prints `root: service started`, starts the terminal, and the banner follows. From here on it supervises the two services. -On a machine without an input path the root task prints `root: no console input, terminal not started`. +On a machine without an input path the root task prints `root: no console input, terminal not started`, starts no service and supervises nothing. The terminal task has its own address space and two capabilities: @@ -107,6 +110,82 @@ The two hostile tasks are the check that the wiring means what it says. They are > [!WARNING] > There is no authentication on the serial line. Whoever holds the line is the operator and can do exactly the operator's four operations, including erasing the key. The operator cannot sign, cannot deliver a seed and cannot change the policy. +## Supervision + +In a terminal image the root task supervises the terminal and the vault. After `root: service started` it does not block for ever. It asks the kernel at a fixed pace whether the two tasks are still alive, takes back everything an ended service was made of, and starts the service again a limited number of times. Images without `terminal` have none of this. + +

+ The root task asks the kernel with TCB_STATUS at every second tick whether the terminal task and the vault task ended. Each service has a seat: a slab of 16 granules and a fixed range of root CNode slots. When a task has ended, the root task revokes the slab, erases the slab if it is the vault, waits, and builds the service again in the same slab and the same slots. After 3 restarts per boot a service stays down. +

+ +The policy is the crate `userspace/k0-sup`. It is `no_std`, forbids `unsafe` code, has no dependencies and makes no system call. It reaches the outside only through the trait `Host`, which has five functions: ask whether a service ended, ask whether a console input path exists, retire a service, rebuild a service and print a line. The root task implements `Host` with system calls in `userspace/root-task/src/service.rs`, and the host tests implement it with a mock. The loop in service and the self-test at boot call the same function, `Supervisor::poll`. + +### Seats + +Each service has a **seat**. A seat is two things: + +- **A slab**: a child untyped of 16 granules that the root task cuts with `UNTYPED_SPLIT` (see [capabilities.md](capabilities.md#untyped-split)). The address space with its page tables, the stack, the CNode and the TCB of the service all come from the slab. That is 14 granules with the 4 KiB granule and 8 with the 16 KiB granule. +- **A range of root CNode slots**: the first build of a seat fixes the range, and every later build uses the same slots. A build that does not end exactly at the end of the range fails the root task's check. + +A rebuild therefore uses the same memory and the same slots, however often it happens. The slabs stay in the root task's CNode. No service gets an untyped capability. + +In an image with a vault, three objects that the services use are outside the slabs: the vault endpoint, the operator response frame and the admin request frame. So a rebuild of one service does not change the address space of the other, and the terminal's send capability to the vault endpoint stays valid when the vault is built again. + +### The poll + +The root task waits on an endpoint that only it holds. No message ever arrives there, so the wait can only end with `TIMEOUT`. It asks for a timeout of 1 tick, which ends at the second tick after the call, so there is one poll at every second tick. The root task never waits on anything a service holds, so a service cannot hold it up. + +At each poll the supervisor asks `TCB_STATUS` for every service that is up (see [scheduling.md](scheduling.md#asking-whether-a-task-ended)). The terminal comes first. A service whose task is `ENDED` is **retired** in the same poll, whether or not it will be started again: + +1. The root task revokes the slab. This removes the task, its CNode, its address space, the page tables and the stack in one call, and the `Tcb` slot must be empty afterwards. +2. For the vault, it erases the slab (see [vault.md](vault.md#when-the-vault-ends)). +3. It empties the slots of the seat. What is left there are copies of image frames, which do not come from the slab. +4. In an image with a vault, it unmaps the views of the shared frames. For the terminal that is the read-only view of the operator response frame. For the vault it is the view of the admin request frame and the response frame itself, and the root task then zeroes the response frame, which can still hold the last public key. The response frame is zeroed only when the vault is retired, not when the terminal is. + +Then the policy decides what happens to the seat: + +- **Restart budget**: each service is started again at most 3 times per boot. The two services have separate budgets, and a budget is never refilled. A restart counts when it is decided, not when it succeeds. +- **Waits**: the service is built again at the first poll after the one that saw the end for restart 1, at the fourth poll after it for restart 2, and at the sixteenth for restart 3. That is at least 2, 8 and 32 ticks, and a tick is one second. +- **No reason**: the policy does not use why a task ended. `TCB_STATUS` gives no reason, and a reason would be chosen by the task that ends. +- **Terminal without input**: the terminal is not started again when the image has no console input path, that is when `CONSOLE_READ` with `NONBLOCK` returns `NO_DEVICE`. This uses no budget. The root task asks only after it has seen the terminal ended and retired it, and once more right before the rebuild. It never asks while the terminal is up, because the question can take a byte from the ring. +- **Vault without terminal**: in service the terminal is the only task that calls the vault. When the terminal is down for good (its budget is spent, or there is no input path), a vault that is still up is stopped and erased in the same poll, and a vault that was waiting for its restart is not built again. The purpose is that a key does not stay in the vault's memory when no task is left to use it. +- **The end**: when nothing is left to supervise, the root task prints `root: supervision over` once and then waits without a timeout. + +A terminal that is started again is a new task: it prints the banner and the prompt again, and the line that was being typed is gone. A vault that is started again has no key (see [vault.md](vault.md#when-the-vault-ends)). + +The supervisor prints nothing while both services are up. It prints the lines of the following table, and no other. `` is 1, 2 or 3, and `` is 2, 8 or 32. + +| Line | Meaning | +| --- | --- | +| `root: terminal ended, restart of 3 after at least ticks` | The terminal task ended and was retired. It will be built again after the wait | +| `root: vault ended and erased, restart of 3 after at least ticks` | The vault task ended, and its slab was retired and erased. It will be built again after the wait | +| `root: terminal started again` | The terminal was built again in its seat | +| `root: vault started again without a key` | The vault was built again in its seat. It holds no seed and no key | +| `root: terminal ended, no console input, not started again` | The terminal ended and there is no console input path | +| `root: terminal ended, restart budget spent, not started again` | The terminal ended a fourth time | +| `root: vault ended and erased, restart budget spent, not started again` | The vault ended a fourth time | +| `root: vault ended and erased, no terminal, not started again` | The vault was waiting for its restart when the terminal went down for good | +| `root: vault stopped and erased, no terminal` | The vault was still up when the terminal went down for good, so the root task stopped and erased it | +| `root: supervision over` | No service is left to supervise | + +A host test of `k0-sup` pins this wording, and another one checks that no line contains a word that `tools/qemu-boot-test.sh` reads as a failure. + +### When a step of the root task fails + +Every step of a build or a retire is checked. If a check fails, the root task prints `root: FAIL ` and exits, as in the self-tests. In an image with a vault it first tries to erase the vault slab: it revokes the slab, retypes all 16 granules as frames, requires that a 17th `RETYPE` returns `EXHAUSTED`, and revokes again. It then prints `root: vault erased before exit` or `root: vault not erased`. This is armed from the moment right before the service vault gets its seed, so it also covers a failed check in the hostile-task run. After the root task has exited nothing supervises the services any more. + +### The restart path at boot + +The retire and rebuild code runs at every boot of a terminal image, before the service starts. It runs with test limits (no wait, one restart) and with the supervisor's lines switched off. + +- **Vault** (images with a vault, `root: vault restart test pass`): the root task builds a vault in the vault seat and checks that it is `fresh`. It ends that vault by revoking its CNode, sees `ENDED` from `TCB_STATUS`, and checks that a call to the endpoint finds no receiver. One call of `Supervisor::poll` then retires the seat, erases the slab and builds a vault again. The root task checks that the same slot holds a living task again, that the new vault reports `zeroized`, and that it refuses `INIT` with a seed whose description claims enough entropy. Then it retires the seat once more, so the service vault is built from nothing in the same seat. The vault of this test never held a secret, and the seed offered to it is a public value. +- **Terminal** (`root: terminal restart test pass`): the two hostile tasks are the first two starts of the terminal seat. The first one ends in a fault, and a poll retires the seat and builds the second one. The second one ends in a fault, and a poll retires the seat and builds nothing, because the test budget of one restart is spent. The seat is empty afterwards. The third start of the seat is the real terminal. The vault is not given to this test supervisor, so the service vault is not erased when the test leaves the terminal seat down. + +For an image with the terminal and the vault, `tools/qemu-boot-test.sh` expects these lines in this order: `root: vault restart test pass`, the `root: vault ` line of the seed, `root: terminal console filter [`, `root: terminal wiring holds`, two `k0: task fault dabort-lower`, `root: terminal restart test pass` and `root: service started`. Without a vault the first two are absent. The number of fault lines per image did not change. + +> [!NOTE] +> The boot self-test runs retire and rebuild with one restart per service and without waits. No committed test makes the real terminal or the real vault end during service, so the timed loop of a real boot is not exercised on a machine (see "Known gaps"). + ## The screen and command rules The screen is plain text. The banner is `K0 operator console, type 'help'`, the prompt is `k0> `, values are printed as `name=value`, and every command ends with exactly one line, `ok` or `err `. @@ -138,13 +217,24 @@ 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 19 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 415 tests on an ARM host and 327 on other hosts. +**Host tests** (`tools/host-test.sh`): `k0-conin` has 19 tests with a fake UART, `k0-term` has 24 with the vault feature and 21 without, `k0-vault` has 22 with Ed25519 and 13 without, and `k0-sup` has 20. The suite has 457 tests on an ARM host and 369 on other hosts. + +The 20 tests of `k0-sup` run the supervisor's policy on a mock host that records every call. They check the following: + +- that a service that stays up is left alone, and that the input path is not asked about while the terminal is up +- that an ended service is retired in the same poll and built again only after its wait, and that the wait grows with every restart +- that the budget ends in a final state, that the two services have separate budgets, and that a service that is down ignores everything +- that a terminal without an input path goes down without using budget, and that the input path is asked about again right before a rebuild +- that a vault that ended is always retired, that a vault that is up is stopped when the terminal is down for good, and that a vault that waits is then not built again +- that the line `root: supervision over` comes once, and only when everything is down +- that over 4000 random histories with five different limits no service is built more often than its budget allows, a service that is down stays down, and supervision never comes back after it is over +- that the lines read exactly as this note quotes them, and that no line contains a word that the boot test reads as a failure **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 82 rows on a Mac with HVF and 71 in CI. -**Scripted session**: `tools/term-test.py ` boots the image with QEMU's serial port on pipes and runs a session. It covers every command and every error, erase and cancel, CR LF, an ESC sequence, a line that is too long, key generation, the public key format, zeroize, 200 kB without a line end, 2000 lines in a row, a serial break and a flood of 2000 breaks. The flood step checks that the input path is not cut off and that the terminal answers again; the bound itself is shown by the host tests. The step runs on QEMU 8.0 or later, so not in CI: an older QEMU puts a break into its PL011 receive FIFO without checking the depth, and breaks pile up there while the kernel keeps the interrupt masked. `tools/qemu-boot-test.sh` reads `K0_BOOT_INPUT=on|off`, `K0_BOOT_SERVICE=vault|plain|none` and a judge-only mode `K0_BOOT_JUDGE`. +**Scripted session**: `tools/term-test.py ` boots the image with QEMU's serial port on pipes and runs a session. It covers every command and every error, erase and cancel, CR LF, an ESC sequence, a line that is too long, key generation, the public key format, zeroize, 200 kB without a line end, 2000 lines in a row, a serial break and a flood of 2000 breaks. The flood step checks that the input path is not cut off and that the terminal answers again; the bound itself is shown by the host tests. The step runs on QEMU 8.0 or later, so not in CI: an older QEMU puts a break into its PL011 receive FIFO without checking the depth, and breaks pile up there while the kernel keeps the interrupt masked. The script also fails a session when `root: ` appears in the output after the prompt. The supervisor prints only when a service ended, so in a healthy session such a line means a restart that should not have happened. No step of the session makes a service end. `tools/qemu-boot-test.sh` reads `K0_BOOT_INPUT=on|off`, `K0_BOOT_SERVICE=vault|plain|none` and a judge-only mode `K0_BOOT_JUDGE`. -**Root task self-test** (images with `console-input`): `root: backspace without the input right [?]` and `root: console input tests pass`. The second line may also read `... pass (no input path)` or `... cut short (the line is busy)` when bytes arrive during the test. A terminal image also shows two more `k0: task fault` lines than the same image without the terminal (8 without the vault, 10 with it). +**Root task self-test** (images with `console-input`): `root: backspace without the input right [?]` and `root: console input tests pass`. The second line may also read `... pass (no input path)` or `... cut short (the line is busy)` when bytes arrive during the test. A terminal image also shows two more `k0: task fault` lines than the same image without the terminal (8 without the vault, 10 with it). It also runs the restart path before the service starts and prints `root: terminal restart test pass`, and `root: vault restart test pass` when a vault is built in (see [The restart path at boot](#the-restart-path-at-boot)). ## Known gaps @@ -162,6 +252,10 @@ The vault side changed with this feature. There are four roles by endpoint badge - **Split screen line**: if a kernel line appears while the operator is typing, the screen line is split but the buffer is whole. Enter runs the whole buffer. - **Lines can be imitated**: any task with `Console` output can still print lines that look like kernel or root task lines, because nothing authenticates the prefix. The terminal can additionally erase within its current line. - **No signing client in service mode**: the key is made and shown, but no other task uses it yet. Client signing is shown by the self-test. -- **No restart**: the terminal and the vault are not restarted if they die. The root task is trusted. +- **Supervision is polling by a trusted task**: the root task is trusted, and nothing supervises the root task. It sees the end of a service at its next poll, so up to two ticks later, and then it still has to get the CPU. A service that hangs without ending looks alive and is not noticed. The kernel still delivers no fault to a handler task. +- **Three restarts per boot**: after the third restart of a service, or when the terminal ends on a machine without an input path, the service stays down until the next boot. When the terminal stays down, the vault is stopped and erased too. +- **No key after a vault restart**: a vault that is started again has no seed and no key, and it takes none (see [vault.md](vault.md#when-the-vault-ends)). The terminal then shows `state=zeroized`, and a new key needs a reboot. +- **The timed loop has no test on a machine**: no committed test makes the real terminal or the real vault end during service. The waits, the budget of three, the stop of the vault when the terminal is down and `root: supervision over` are covered only by the host tests of `k0-sup` with a mock host. The boot self-test covers retire, erase and rebuild on the real kernel, with one restart per service and without waits. `root: vault erased before exit` and `root: vault not erased` have no test either. +- **After the end of supervision**: when the root task waits without a timeout and no task waits for console input, the kernel's idle rule prints `k0: all tasks stopped (none ready, no timeout pending)` once (see [scheduling.md](scheduling.md#when-there-is-nothing-left-to-run)). No committed test runs this. - **Boot log share**: terminal output counts against the user share of the in-memory boot log. Once that share is full, later task output is not recorded there. - **All earlier limits of the vault stay**: the implementation is unvalidated, there is no side-channel analysis, the key does not come from an approved random bit generator, there is no persistence and there is no post-quantum algorithm. Availability is not protected (see [ipc.md](ipc.md)). diff --git a/design/en/uefi.md b/design/en/uefi.md index a7c7068..2a61ebf 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 415 tests on an ARM host (`k0-abi` 15, `k0-cap` 54, `k0-boot` 85, `k0-efi` 33, `k0-conin` 19, `k0-slice` 9, `k0-part` 36, `k0-vault` 20 with Ed25519 and 11 without, `k0-term` 24 with the vault feature and 21 without, and `k0-mm` 44 for each of the two granules) and 327 on other hosts, where the `k0-mm` tests are skipped. +- **Host test script**: `tools/host-test.sh` now runs 457 tests on an ARM host (`k0-abi` 16, `k0-cap` 71, `k0-boot` 85, `k0-efi` 33, `k0-conin` 19, `k0-slice` 9, `k0-part` 36, `k0-sup` 20, `k0-vault` 22 with Ed25519 and 13 without, `k0-term` 24 with the vault feature and 21 without, and `k0-mm` 44 for each of the two granules) and 369 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 89d2101..8f4bea5 100644 --- a/design/en/vault.md +++ b/design/en/vault.md @@ -6,7 +6,7 @@ English | [한국어](../kr/vault_KR.md) -This note describes the first service on top of K0's isolation core. A **vault** task holds one Ed25519 key. Client tasks get signatures and the public key over IPC, and they never get the key. The code is in `userspace/k0-vault` (the crate), `userspace/root-task/src/oracle.rs` (wiring and self-test), `userspace/root-task/src/service.rs` (the service that starts after the self-tests) and `crates/k0-boot` (the boot seed). In an image built with `terminal`, the operator of the vault is the serial terminal (see "The service vault and the operator"). +This note describes the first service on top of K0's isolation core. A **vault** task holds one Ed25519 key. Client tasks get signatures and the public key over IPC, and they never get the key. The code is in `userspace/k0-vault` (the crate), `userspace/root-task/src/oracle.rs` (wiring and self-test), `userspace/root-task/src/service.rs` (the service that starts after the self-tests, and its supervision) and `crates/k0-boot` (the boot seed). In an image built with `terminal`, the operator of the vault is the serial terminal (see "The service vault and the operator"). > [!NOTE] > The vault is optional and off by default. The default image has no vault and no crypto code. @@ -75,7 +75,7 @@ The state machine is `Vault::handle` in `userspace/k0-vault/src/server.rs`. The | `fresh` | no seed and no key | | `seeded` | `INIT` delivered a seed that passed the entropy rule, and the vault holds it | | `ready` | `KEYGEN` made the key and wiped the seed | -| `zeroized` | `ZEROIZE` wiped the key and the seed. Only a reboot makes a new key | +| `zeroized` | `ZEROIZE` wiped the key and the seed, or the vault was started again after it ended (see [When the vault ends](#when-the-vault-ends)). Only a reboot makes a new key | | `failed` | a self-test or the pairwise test failed. Every way into this state wipes the seed and the key | There is one key per boot. A second `KEYGEN` is refused with `KEY_EXISTS` (`key-exists` on the terminal). @@ -119,15 +119,39 @@ The seed is delivered in the root task's entry registers `x0` to `x3`. `x4` hold ## The service vault and the operator -The real boot seed is used exactly once. In an image built with `terminal` and `vault`, the root task first runs all self-tests. Then it starts a new vault, the **service vault**, and hands it the boot seed with `INIT`. It prints `root: vault seeded`, or `root: vault has no seed (boot seed has no entropy)`, or `root: vault has no seed (no algorithm in this image)`. In every other image the root task wipes the seed at entry. +The real boot seed is used exactly once. In an image built with `terminal` and `vault`, the root task first runs all self-tests. It then tries the restart path on a vault that never gets a seed (`root: vault restart test pass`, see [terminal.md](terminal.md#the-restart-path-at-boot)). After that it starts a new vault, the **service vault**, and hands it the boot seed with `INIT`. It prints `root: vault seeded`, or `root: vault has no seed (boot seed has no entropy)`, or `root: vault has no seed (no algorithm in this image)`. After the hand-over the root task wipes its own copy of the seed and the request frame it used. In every other image the root task wipes the seed at entry. -The root task then runs two hostile tasks that are wired exactly like the terminal. They must be refused and end in a fault. After that it drops its own admin capability, starts the terminal and blocks for ever. The terminal can ask the service vault for `STATUS`, `PUBLIC_KEY`, `KEYGEN` and `ZEROIZE` through the operator badge, and for nothing else. The commands, the screen and the limits of the terminal are described in [USAGE.md](../../USAGE.md). +The root task then runs two hostile tasks that are wired exactly like the terminal. They must be refused and end in a fault. After that it checks that the service vault is still in the same state, drops its own admin capability and starts the terminal. From then on it supervises both services (see [terminal.md](terminal.md#supervision)). The terminal can ask the service vault for `STATUS`, `PUBLIC_KEY`, `KEYGEN` and `ZEROIZE` through the operator badge, and for nothing else. The commands, the screen and the limits of the terminal are described in [USAGE.md](../../USAGE.md). > [!WARNING] > The serial line has no authentication. Whoever holds the line is the operator and can run exactly the four operator operations, including erasing the key. The operator cannot get a signature and cannot change the policy. The self-test vault is a different vault. It makes its key from the public RFC 8032 test seed, with the real seed info, so the entropy rule is still exercised, and the real seed never reaches it. +### When the vault ends + +The root task asks the kernel at every second tick whether the service vault is still alive (see [terminal.md](terminal.md#supervision)). When the vault task has ended, whatever the reason, the root task erases the vault's memory before it does anything else with that memory: + +1. It revokes the vault's slab. The slab is a child untyped of 16 granules in the root task's CNode, and the address space, the stack, the CNode and the TCB of the vault all came from it. The revoke removes all of them. +2. It retypes all 16 granules of the slab as frames and holds all of them. `CAP_REVOKE` does not zero memory, and `RETYPE` zeroes each granule it hands out. A 17th `RETYPE` must return `EXHAUSTED`, which shows that the 16 frames cover the whole slab. +3. It revokes the slab again, so the frames are gone and the slab is empty. +4. It zeroes the operator response frame. That frame is outside the slab and can still hold the last public key. + +The same steps run when the root task stops a vault that is still up, because the terminal is down for good. Steps 1 to 3 also run, as an attempt, right before the root task exits on a failed check after the service vault got its seed. The root task then prints `root: vault erased before exit` or `root: vault not erased`. + +If the restart budget of three allows it, the root task builds a vault again in the same slab and the same slots, after a wait. That vault is made by `Vault::retired` in `userspace/k0-vault/src/server.rs`: + +- **State**: it runs the self-test like every vault and then starts in the state `zeroized`, not `fresh`. If the self-test fails it is `failed`. +- **No seed**: it refuses `INIT`, also from the admin, with `DENIED`. A `fresh` vault would look like a vault that can still take a seed. +- **No key**: `KEYGEN`, `SIGN` and `PUBLIC_KEY` get the answer of an erased vault (`ZEROIZED`, or `UNSUPPORTED` in an image without an algorithm). `STATUS` and `ZEROIZE` still work. + +The root task has no seed to give a second time. It handed the boot seed to the first service vault once, wiped its own copy, and dropped its admin capability before the service started. + +> [!IMPORTANT] +> After a vault restart there is no key until the machine is booted again. The log line is `root: vault started again without a key`, and on the terminal `vault status` shows `state=zeroized`. + +With `vault-ed25519`, `vault keygen ed25519` and `vault pubkey` then answer `err zeroized`. While no vault is running, between the end of one and the start of the next, a vault command on the terminal finds no receiver. If no vault takes the call within the terminal's timeout of 5 ticks, the command answers `err vault-timeout`. + ## Features and the fixed image The `k0-kernel` crate has two features, and features only add: @@ -151,12 +175,12 @@ $ cargo build -p k0-kernel --features console,vault-ed25519 ## How it is tested -**Host tests** (`tools/host-test.sh` runs `k0-vault` with and without the algorithm feature). The tests are in `userspace/k0-vault/src/tests.rs`: 20 with Ed25519 and 11 without. The test names are the following: +**Host tests** (`tools/host-test.sh` runs `k0-vault` with and without the algorithm feature). The tests are in `userspace/k0-vault/src/tests.rs`: 22 with Ed25519 and 13 without. The test names are the following: -- 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). +- 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`, `a_vault_started_again_takes_no_seed_and_makes_no_key`, `a_fresh_vault_and_one_started_again_differ_only_in_the_state`, 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 415 tests on an ARM host and 327 on other hosts (without `k0-mm`). +With the other crates, the host suite has 457 tests on an ARM host and 369 on other hosts (without `k0-mm`). The policy that decides when a vault is retired and started again is in `userspace/k0-sup` and has 20 host tests of its own (see [terminal.md](terminal.md#how-it-is-tested)). **Root task self-test** (`test_oracle` in `userspace/root-task/src/oracle.rs`, only in images built with `vault`). It checks the following: @@ -173,6 +197,8 @@ With the other crates, the host suite has 415 tests on an ARM host and 327 on ot The marker is `root: oracle tests pass`. The client tasks run one after another in one client address space, because root CNode slots are scarce. The test shows isolation between the vault and a client, not between clients. +**Restart test at boot** (only in images built with `terminal` and `vault`, marker `root: vault restart test pass`). Before the service vault exists, the root task builds a vault in the same seat, ends it, and lets one poll of the supervisor retire, erase and rebuild it. It then checks that the new vault reports `zeroized` and refuses `INIT`. The steps are in [terminal.md](terminal.md#the-restart-path-at-boot). This test does not read the erased memory back. That a slab which was revoked and retyped reads as zero is checked on another slab, by the split self-test of every image, which reads four of its 24 granules (`root: untyped split tests pass`, see [capabilities.md](capabilities.md#how-it-is-tested)). + **Boot matrix rows**: `vault`, `vault-max` (RNDR), `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`, and the static row `vault-symbols` (the default image has no vault or crypto code, and the vault image has no writable static from them). The matrix has 82 rows on a Mac with HVF and 71 in CI. The rows for the terminal are `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi` and `hvf-term`. `tools/term-test.py ` boots a terminal image with QEMU's serial port on pipes and runs a scripted session. Every image now also prints `k0: dtb seeds wiped B` and `root: boot seed from rng-seed bytes ...`. ## Known gaps @@ -182,7 +208,10 @@ 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. +- **A restarted vault has no key**: the supervisor starts a vault that ended again, at most three times per boot, but the new vault has no seed and no key and takes none. The key of the vault that ended is gone, and a new key needs a reboot. +- **The erase is not read back in service**: the root task erases the slab of an ended vault by retyping all of it, and checks that 16 frames cover it. It does not map the frames and read them. What lies outside the slab is not covered by this erase: the root task zeroes the operator response frame separately, and copies of the seed that the firmware or the UEFI loader keep are not wiped (see the note in the boot seed section). +- **No test ends the real vault**: no committed test makes the service vault end during service. The restart path runs at every boot on a vault without a seed, once and without waits, and the timed policy is tested on the host with a mock (see [terminal.md](terminal.md#known-gaps)). +- **A vault that hangs is not noticed**: the supervisor sees only a task that ended, and it sees it up to two ticks late. - **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 domain of its own**: the vault is not in a time partition domain of its own yet. The root task deletes the control capability of the time partitions at the end of its self-tests, so the vault, its clients and the terminal all run in the root domain, and what they learn about each other through the scheduler is not limited (see [scheduling.md](scheduling.md#time-partitions)). diff --git a/design/kr/README.md b/design/kr/README.md index 3dd2db1..bea9633 100644 --- a/design/kr/README.md +++ b/design/kr/README.md @@ -18,15 +18,15 @@ | [boot_KR.md](boot_KR.md) | 첫 명령에서 루트 태스크까지: 코어 선택, EL1로의 하강, higher-half로의 점프, 고정된 초기화 순서 | | [memory_KR.md](memory_KR.md) | 커널 페이지 테이블, 부팅용 테이블 풀, 테이블 예약 구간과 롤백, W^X, 가드 페이지, 부팅 시 변환 검사 | | [user-address-space_KR.md](user-address-space_KR.md) | `AddrSpace` 오브젝트와 등록부, 사용자 권한, 커널이 테이블을 할당하지 않는 `MAP`과 `UNMAP`, 케이퍼빌리티가 제거될 때 매핑을 정리하는 방법 | -| [capabilities_KR.md](capabilities_KR.md) | 태스크별 CNode, 권한과 배지, 파생 목록, untyped 메모리, retype과 실패 시 보장, revoke와 delete, 태스크 격리가 다루는 것과 다루지 않는 것 | +| [capabilities_KR.md](capabilities_KR.md) | 태스크별 CNode, 권한과 배지, 파생 목록, untyped 메모리, retype과 실패 시 보장, untyped를 분할해 태스크의 메모리 예산으로 주는 방법, revoke와 delete, 태스크 격리가 다루는 것과 다루지 않는 것 | | [dtb_KR.md](dtb_KR.md) | 적대적 입력으로서의 디바이스 트리: 파서가 읽는 것, 한계, 퍼징 방법 | | [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 권한, 대기와 깨우기, 터미널의 연결과 적대적 태스크 점검, 화면과 명령 규칙, 테스트, 알려진 공백 | +| [vault_KR.md](vault_KR.md) | 서명 오라클: 볼트 태스크와 프레임, `CALL` 프로토콜과 nonce, 고정된 배지 정책, 프로바이더 경계, 부팅 시드와 지우기, 볼트가 끝날 때 키가 어떻게 되는지, feature, 테스트, 알려진 공백 | +| [terminal_KR.md](terminal_KR.md) | 시리얼 입력과 운영자 터미널: 커널이 입력을 받는 이유, 수신 링과 그 한계, `CONSOLE_READ`와 Console 권한, 대기와 깨우기, 터미널의 연결과 적대적 태스크 점검, 루트 태스크가 터미널과 볼트를 감독하고 다시 시작하는 방법, 화면과 명령 규칙, 테스트, 알려진 공백 | 모든 노트는 "**알려진 공백**" 절로 끝납니다. 열려 있는 보안 어드바이저리는 [SECURITY_KR.md](../../SECURITY_KR.md)에 정리되어 있습니다. diff --git a/design/kr/capabilities_KR.md b/design/kr/capabilities_KR.md index bd73b14..26896ef 100644 --- a/design/kr/capabilities_KR.md +++ b/design/kr/capabilities_KR.md @@ -11,6 +11,7 @@ - 슬롯 형식과 태스크별 CNode - 부팅 시 남은 메모리가 untyped 케이퍼빌리티가 되는 과정 - 사용자 공간이 `RETYPE`으로 untyped 메모리를 커널 오브젝트로 바꾸는 방법 +- 사용자 공간이 `UNTYPED_SPLIT`으로 큰 untyped 케이퍼빌리티에서 더 작은 untyped 케이퍼빌리티를 잘라내는 방법 - 파생 리스트, 그리고 복사·이동·삭제·회수의 동작 관련 코드는 다음 표의 파일에 있습니다. @@ -59,7 +60,7 @@ | 종류 | 생성 시점 | 부여하는 권한 | | --- | --- | --- | -| `Untyped` | 부팅 시 | retype할 수 있는 물리 메모리 구간 | +| `Untyped` | 부팅 시, 그리고 다른 untyped에서 `UNTYPED_SPLIT`으로 | retype하고 분할할 수 있는 물리 메모리 구간 | | `Frame` | `RETYPE`으로, 그리고 루트 태스크 이미지용으로 부팅 시 | 주소 공간에 매핑할 수 있는 1 그래뉼의 메모리 | | `PageTable` | `RETYPE`으로 | 주소 공간에 설치할 수 있는 페이지 테이블 하나 | | `Tcb` | `RETYPE`으로, 그리고 루트 태스크용으로 부팅 시 | 설정하고 재개할 수 있는 태스크 | @@ -90,7 +91,7 @@ ### 원본 플래그 -`RETYPE`이나 부팅이 만든 케이퍼빌리티는 그 오브젝트의 **원본**(original)입니다. 원본은 오브젝트마다 정확히 하나뿐이며, 복사본은 원본이 될 수 없습니다. 오브젝트는 원본 케이퍼빌리티가 제거될 때 종료됩니다("종료 처리" 참고). TCB의 내장 슬롯에 들어간 케이퍼빌리티에는 그 태스크에 묶였다는 표시도 붙습니다. +`RETYPE`이나 부팅이 만든 케이퍼빌리티는 그 오브젝트의 **원본**(original)입니다. 원본은 오브젝트마다 정확히 하나뿐이며, 복사본은 원본이 될 수 없습니다. `UNTYPED_SPLIT`이 만드는 자식 untyped에도 이 플래그가 붙습니다. 오브젝트는 원본 케이퍼빌리티가 제거될 때 종료됩니다("종료 처리" 참고). TCB의 내장 슬롯에 들어간 케이퍼빌리티에는 그 태스크에 묶였다는 표시도 붙습니다. ## CNode @@ -157,7 +158,7 @@ untyped 케이퍼빌리티는 디바이스 트리가 보고한 RAM의 모든 바 각 untyped 케이퍼빌리티에는 **워터마크**가 있습니다. 베이스부터 세어 얼마나 사용했는지를 나타내는 값입니다. retype은 워터마크를 그래뉼 단위로 올림하고, 다음 그래뉼을 새 오브젝트로 가져가며, 워터마크를 그 뒤로 옮깁니다. 새 케이퍼빌리티는 그 오브젝트의 원본이고, 파생 리스트에 **untyped의 자식**으로 들어갑니다. -살아 있는 자식이 있는 동안에는 워터마크가 증가만 합니다. 그래서 같은 untyped 케이퍼빌리티에서 떼어 낸 살아 있는 두 오브젝트는 겹치지 않습니다. untyped는 쪼갤 수 없습니다. +살아 있는 자식이 있는 동안에는 워터마크가 증가만 합니다. 그래서 같은 untyped 케이퍼빌리티에서 떼어 낸 살아 있는 두 오브젝트는 겹치지 않습니다. `UNTYPED_SPLIT`은 같은 워터마크에서 더 작은 untyped 케이퍼빌리티를 잘라내며, 그 자식도 오브젝트와 똑같이 untyped의 자식으로 셉니다([Untyped 분할](#untyped-분할) 참고). 다음 순서로 검사하며, 순서가 중요합니다. @@ -189,6 +190,62 @@ untyped 케이퍼빌리티는 디바이스 트리가 보고한 RAM의 모든 바 untyped에서 파생된 것이 모두 사라지면 메모리가 그 untyped로 돌아옵니다. `RETYPE` 시점에 untyped에 자손이 없으면 그 구간을 차지한 살아 있는 오브젝트가 없다는 뜻이므로 워터마크를 베이스로 되돌립니다. 보통은 태스크가 untyped에 `CAP_REVOKE`를 호출해 거기서 잘라낸 오브젝트를 전부 종료시킨 뒤 같은 메모리를 다시 retype합니다. 메모리는 그때마다 다시 0으로 채워집니다. +자식 untyped도 자손입니다. 오브젝트가 하나도 남지 않았더라도 자식 untyped가 하나라도 있으면 그 untyped의 구간은 처음부터 다시 시작하지 않습니다. + +`CAP_REVOKE`와 `CAP_DELETE`는 풀어 준 메모리를 0으로 채우지 않습니다. 그래뉼은 `RETYPE`이 그것으로 다음 오브젝트를 만들 때 0으로 채워집니다. 다시 retype되지 않은 그래뉼에는 이전 내용이 남아 있을 수 있으므로, 풀려난 구간을 지워야 하는 태스크는 그 구간의 그래뉼을 전부 retype해야 합니다([자식의 회수와 삭제](#자식의-회수와-삭제) 참고). + +## Untyped 분할 + +`UNTYPED_SPLIT(untyped, granules, dest)`는 시스템 콜 19번입니다. untyped 케이퍼빌리티(**부모**)에서 더 작은 untyped 케이퍼빌리티(**자식**)를 잘라냅니다. 자식만 가진 태스크는 자식의 구간에서만 오브젝트를 만들 수 있고 다른 곳에서는 만들 수 없습니다. 태스크에 메모리 예산을 주는 방법이 이것입니다. + +| 레지스터 | 내용 | +| --- | --- | +| `x0` | 부모인 untyped 케이퍼빌리티의 슬롯 | +| `x1` | 그래뉼 단위로 센 자식의 크기(1 이상) | +| `x2` | 자식을 받을 빈 슬롯 | + +두 슬롯 모두 호출자의 CNode 안에 있습니다. `x3`부터 `x5`는 읽지 않습니다. `x0`의 결과는 0 또는 에러 코드입니다. + +자식은 부모의 워터마크를 그래뉼 단위로 올림한 자리에서 시작하고 길이는 정확히 `x1` 그래뉼입니다. 부모의 워터마크는 그 뒤로 옮겨 갑니다. 부모에 자손이 없으면 `RETYPE`과 마찬가지로 워터마크를 먼저 베이스로 되돌립니다. 이 호출이 바꾸는 것은 두 슬롯뿐입니다. 메모리를 건드리지 않고, 커널 자원을 사용하지 않으며, 상수 시간에 끝납니다. 자식의 메모리는 나중에 `RETYPE`이 그것으로 오브젝트를 만들 때 그래뉼 단위로 0으로 채워집니다. + +자식은 원본 케이퍼빌리티입니다. 파생 리스트에서 부모 바로 뒤에 한 단계 깊게 들어가고, 자식 자신의 워터마크는 0에서 시작합니다. 자식에는 다음 규칙이 적용됩니다. + +- **정확한 크기**: 모든 오브젝트는 1 그래뉼이므로 n 그래뉼짜리 자식에서는 오브젝트가 정확히 n개 나오고 그 뒤로는 `EXHAUSTED`입니다. 부모에는 구간의 나머지가 남습니다. +- **겹치지 않음**: 자식은 부모의 워터마크 아래에 있으므로, 자식이 있는 동안 부모는 그 구간을 다른 것에 내주지 않습니다. 한 부모의 자식과 오브젝트는 겹치지 않습니다. +- **다시 분할**: 자식도 다른 untyped처럼 분할할 수 있습니다. 자식과 그 자식의 자식들에서 나오는 오브젝트를 모두 합쳐도 자식의 그래뉼 수를 넘지 않습니다. +- **복사 불가**: 자식은 다른 untyped와 마찬가지로 복사할 수 없습니다(`BAD_CAP`). 그래서 한 구간에는 언제나 워터마크가 하나입니다. +- **이동**: `CAP_MOVE`로 자식을 다른 CNode에 넣을 수 있고, 자손은 파생 리스트에서 그 아래에 그대로 남습니다. 자식을 다른 태스크의 CNode로 옮기면 그 태스크의 예산이 됩니다. 옮긴 태스크는 그 뒤로 자식을 지칭할 수 없으며, 부모를 회수해서 메모리를 되찾습니다. + +`RETYPE`은 바뀌지 않았고 `bootinfo::VERSION`은 5 그대로입니다. 루트 태스크는 감독하는 서비스마다 자식 untyped 하나를 슬랩으로 사용합니다([terminal_KR.md](terminal_KR.md#감독) 참고). + +### 자식의 회수와 삭제 + +- **자식에 CAP_REVOKE**: 자식에서 만든 것을 전부 제거하고 자식은 남깁니다. 메모리는 부모가 아니라 자식에게 돌아갑니다. 자식에 자손이 없어졌으므로 다음 `RETYPE`이나 분할은 다시 자식의 베이스에서 시작합니다. 부모의 워터마크는 바뀌지 않습니다. +- **자식에 CAP_DELETE**: 자식과 자식에서 만든 것을 전부 제거합니다. 부모는 그 순간에 구간을 돌려받지 않습니다. 부모는 자손이 하나도 없을 때에만 베이스에서 다시 시작하며, 이것은 [메모리 재사용](#메모리-재사용)의 규칙입니다. +- **부모에 CAP_REVOKE**: 자식들, 그 자식의 자식들, 그 어느 것에서든 만든 오브젝트 전부를 한 번의 호출로 제거합니다. +- **자기가 만든 것 안에 놓인 자식**: 회수되는 자식의 슬롯이 같은 회수가 종료시키는 CNode 안에 있으면 자식도 함께 삭제됩니다. 자식을 어떤 태스크의 CNode로 옮겼는데 그 CNode가 같은 자식에서 만든 것일 때가 그렇습니다. 종료되는 CNode의 슬롯은 무엇이 들어 있든 전부 비워집니다. +- **자식 지우기**: 회수는 구간을 지우지 않습니다. 회수한 자식의 구간 전체를 지우려면 그 그래뉼을 전부 retype하고, 마지막 것을 만들 때까지 새 케이퍼빌리티를 전부 쥐고 있어야 합니다. 오브젝트를 하나씩 만들고 삭제하면 삭제할 때마다 자식에 자손이 없어져서, 자식이 첫 그래뉼만 거듭 내줍니다. + +자식은 메모리를 제한하고, 그에 따라 자식을 가진 쪽이 한 번에 가질 수 있는 오브젝트 수를 제한합니다. 시간은 제한하지 않습니다. 커널은 여전히 선점되지 않고, `CAP_REVOKE`와 `CAP_DELETE`는 여전히 제거하는 케이퍼빌리티 수에 비례하는 시간이 걸립니다. 복사본도 그 수에 들어가므로 자식의 크기만으로는 그 수가 제한되지 않습니다. 중간에 끊었다가 이어서 할 수 있는 회수는 아직 없습니다. + +> [!NOTE] +> 자식 untyped는 메모리의 예산이지 시간의 예산이 아닙니다. 자식에 대한 `CAP_REVOKE`와 `CAP_DELETE`는 제거하는 케이퍼빌리티 수만큼 오래 걸리고, 커널은 선점되지 않습니다. + +### UNTYPED_SPLIT의 에러 + +검사는 다음 표의 순서로 진행됩니다. 거부된 호출은 아무것도 바꾸지 않습니다. + +| 코드 | 원인 | +| --- | --- | +| `BAD_SIZE` (-27) | `x1`이 0임. 슬롯을 보기 전에 검사함 | +| `BAD_SLOT` | 부모나 목적지의 슬롯 번호가 0이거나 범위 밖임 | +| `NOT_UNTYPED` | 부모 슬롯이 비어 있거나 다른 종류의 케이퍼빌리티를 담고 있음 | +| `OCCUPIED` | 목적지 슬롯에 케이퍼빌리티가 있음. 부모 자신의 슬롯도 여기에 해당함 | +| `EXHAUSTED` | 부모에 남은 자리가 모자라거나, 크기가 오버플로하거나, 자식의 마지막 그래뉼이 오브젝트의 주소가 될 수 없음 | +| `TOO_DEEP` | 자식이 깊이 상한 `MAX_DEPTH`를 넘게 됨 | + +이 호출은 커널 테이블을 사용하지 않으므로 `KERNEL_RESOURCE`로 실패할 수 없습니다. + ## 파생 리스트 모든 케이퍼빌리티는 전위 순서의 이중 연결 리스트 하나에 엮이고, 슬롯마다 깊이를 저장합니다. 슬롯의 자손은 바로 뒤에 이어지면서 더 깊은 슬롯들이므로, 트리나 할당 없이 찾을 수 있습니다. 다음 그림은 부팅 케이퍼빌리티에서 시작해 `RETYPE`과 `CAP_COPY`로 리스트가 자라는 모습과, `CAP_REVOKE` 및 `CAP_DELETE`의 역할을 보여 줍니다. @@ -201,10 +258,11 @@ untyped에서 파생된 것이 모두 사라지면 메모리가 그 untyped로 - **부트 케이퍼빌리티**: 각자 독립된 리스트의 뿌리(깊이 0)입니다. - **RETYPE**: 새 케이퍼빌리티를 untyped 바로 뒤에, 한 단계 깊게 추가합니다. +- **UNTYPED_SPLIT**: 자식 untyped를 부모 바로 뒤에, 한 단계 깊게 추가합니다. - **CAP_COPY**: 복사본을 원본 바로 뒤에, 한 단계 깊게 추가합니다. 복사본은 **원본의 자식**입니다. 그래서 부모를 회수하면 복사본이 함께 사라지고, 복사본이 원본보다 오래 살 수 없습니다. - **CAP_MOVE**: 리스트에서의 위치, 깊이, 플래그, 매핑 기록을 그대로 유지합니다. -깊이는 `MAX_DEPTH`로 제한됩니다. 이를 넘는 `CAP_COPY`나 `RETYPE`은 `TOO_DEEP`으로 실패하므로 깊이 카운터는 넘치지 않습니다. 모든 리스트 연산은 이웃이 이 슬롯을 되가리키는지 확인합니다. 링크가 어긋나 있으면 아무것도 바꾸지 않고 `k0: FATAL cap derivation list corrupt`를 출력하며 정지합니다. +깊이는 `MAX_DEPTH`로 제한됩니다. 이를 넘는 `CAP_COPY`, `RETYPE`, `UNTYPED_SPLIT`은 `TOO_DEEP`으로 실패하므로 깊이 카운터는 넘치지 않습니다. 모든 리스트 연산은 이웃이 이 슬롯을 되가리키는지 확인합니다. 링크가 어긋나 있으면 아무것도 바꾸지 않고 `k0: FATAL cap derivation list corrupt`를 출력하며 정지합니다. ## 복사, 이동, 삭제, 회수 @@ -226,7 +284,7 @@ untyped에서 파생된 것이 모두 사라지면 메모리가 그 untyped로 > [!WARNING] > K0에서는 어떤 케이퍼빌리티를 삭제하든 거기서 파생된 것이 전부 함께 삭제됩니다. 복사본은 원본보다 오래 살지 못하고, 오브젝트는 원본 케이퍼빌리티와 함께 죽습니다. -untyped를 회수하면 거기서 잘라낸 것이 전부 종료됩니다. 조상 하나를 한 번 회수하는 동안 오브젝트의 원본이 복사본보다 먼저 제거될 수 있으므로, 종료 처리 콜백은 이미 종료된 오브젝트의 복사본에 대한 콜백도 견뎌야 합니다. 그 전부가 시스템 콜이 반환하기 전에 사라집니다. +untyped를 회수하면 거기서 잘라낸 것이 전부 종료되고, 자식 untyped 케이퍼빌리티도 거기서 만든 것 전부와 함께 제거됩니다([자식의 회수와 삭제](#자식의-회수와-삭제) 참고). 조상 하나를 한 번 회수하는 동안 오브젝트의 원본이 복사본보다 먼저 제거될 수 있으므로, 종료 처리 콜백은 이미 종료된 오브젝트의 복사본에 대한 콜백도 견뎌야 합니다. 그 전부가 시스템 콜이 반환하기 전에 사라집니다. ## 종료 처리와 보류 목록 @@ -255,10 +313,12 @@ untyped를 회수하면 거기서 잘라낸 것이 전부 종료됩니다. 조 | `DEBUG_PUTC` | `W`가 있는 `Console` | | `CONSOLE_READ` | `R`이 있는 `Console`(`console-input`으로 빌드한 이미지에만 있음) | | `RETYPE` | `Untyped`, 그리고 호출자 CNode의 빈 목적지 슬롯 | +| `UNTYPED_SPLIT` | `Untyped`, 그리고 호출자 CNode의 빈 목적지 슬롯 | | `MAP` | 권한이 요청한 매핑을 덮는 `Frame`(`RO`는 `R`, `RW`는 `R\|W`, `RX`는 `R\|X` 필요) 또는 `PageTable`, 그리고 타겟을 지정하는 `AddrSpace` | | `UNMAP` | 매핑된 `Frame` 또는 `PageTable` | | `TCB_CONFIGURE` | `Inactive` 상태의 `Tcb`, `AddrSpace`, `CNode` | | `TCB_RESUME` | `Stopped` 상태의 `Tcb` | +| `TCB_STATUS` | 어느 상태든 `Tcb`([scheduling_KR.md](scheduling_KR.md#태스크가-끝났는지-묻기) 참고) | | `PART_SET_TABLE` | `PartCtl` | | `PART_SET_DOMAIN` | `PartCtl`, 그리고 `Stopped` 상태의 `Tcb` | | `SEND`, `CALL` | `W`를 가진 `Endpoint` | @@ -282,7 +342,8 @@ untyped를 회수하면 거기서 잘라낸 것이 전부 종료됩니다. 조 | --- | --- | | `BAD_SLOT` | 슬롯 번호가 0이거나 범위 밖이거나 슬롯이 비어 있음(태스크에 CNode가 묶여 있지 않을 때도 해당) | | `BAD_CAP` | 슬롯의 케이퍼빌리티 종류가 맞지 않거나 복사나 이동이 불가능한 것 | -| `NOT_UNTYPED` | `RETYPE`의 소스가 untyped가 아님 | +| `NOT_UNTYPED` | `RETYPE`이나 `UNTYPED_SPLIT`의 소스가 untyped가 아님 | +| `BAD_SIZE` (-27) | `UNTYPED_SPLIT`의 그래뉼 수가 0임 | | `OCCUPIED` | 목적지 슬롯이 비어 있지 않음(예전 `OUT_OF_SLOTS`를 대체하며 값은 그대로 -4) | | `NO_RIGHTS` | 호출에 필요한 권한이 케이퍼빌리티에 없거나, 복사 마스크로 남는 권한이 없음 | | `BAD_PERM` | 매핑 권한이나 권한 마스크 값이 올바르지 않음 | @@ -310,15 +371,31 @@ untyped를 회수하면 거기서 잘라낸 것이 전부 종료됩니다. 조 - 쌍 복사가 전부 아니면 전무인지 - 깊이가 제한되는지 - 링크가 어긋나면 연산이 멈추는지 -- **모델 테스트**: `random_operation_sequences_keep_every_invariant`는 두 그래뉼에 걸쳐 retype, 복사, 이동, 쌍 바인딩, 삭제, 회수를 무작위로 이어 붙인 열(260단계짜리 월드 160개)을 실행합니다. 매 단계 뒤에 다음을 검사합니다. +- **분할의 호스트 단위 테스트**: `k0-cap`의 테스트 71개 가운데 17개가 `UNTYPED_SPLIT`에 관한 것입니다. 다음을 검사합니다. + - 자식이 부모의 워터마크에서 그래뉼 경계에 맞춰 시작하고 부모의 워터마크가 그 뒤로 옮겨 가는지 + - 거부된 분할이 두 슬롯을 그대로 두는지(오버플로하는 크기와 주소 공간 꼭대기 근처의 구간 포함) + - 마지막 그래뉼이 오브젝트의 주소가 될 수 없는 자식이 만들어지지 않는지 + - 자식에서 정확히 그 그래뉼 수만큼 나오고 부모에 나머지가 남는지 + - 한 부모의 자식과 오브젝트가 겹치지 않는지 + - 자식을 회수하면 부모가 아니라 자식이 처음부터 다시 시작하는지 + - 자식을 삭제해도 부모에 자손이 없어질 때까지는 아무것도 돌아오지 않는지 + - 자식을 복사할 수 없고, 옮기면 그 아래의 것이 전부 함께 가는지 + - 조상을 회수하면 중첩된 자식과 그 오브젝트가 제거되는지 + - 분할의 깊이가 제한되는지 + - 회수한 슬랩을 같은 자리에서 라운드마다 다시 쓸 수 있는지(`the_supervisor_recipe_reuses_the_slab_in_place`) + - 자식에서 만든 CNode 안에 슬롯이 놓인 자식이 자기 회수로 삭제되는지, 부모의 슬롯이 거기에 놓여 있으면 같은 회수가 부모를 삭제하는지 + - 자식 untyped의 제거가 원본으로서 한 번만 보고되는지 + - 회수한 자식을 지우려면 그 그래뉼을 전부 쥐고 있어야 하는지 +- **모델 테스트**: `random_operation_sequences_keep_every_invariant`는 두 그래뉼에 걸쳐 retype, 분할, 복사, 이동, 쌍 바인딩, 삭제, 회수를 무작위로 이어 붙인 열(260단계짜리 월드 160개)을 실행합니다. 매 단계 뒤에 다음을 검사합니다. - 리스트가 올바른 전위 순서인지 - 살아 있는 오브젝트마다 원본이 정확히 하나인지 - 종료된 오브젝트를 가리키는 케이퍼빌리티가 없는지 - 파괴된 슬롯 배열이 비어 있는지 - retype이 살아 있는 오브젝트의 메모리를 내주지 않는지 + - 자식 untyped가 온전한 그래뉼들로 이루어지고 한 untyped의 자식들이 겹치지 않는지 - 또한 이 열이 종료, 태스크 해체, 메모리 재사용 경로를 충분히 밟았는지도 확인합니다. 두 번째 테스트(`revoking_every_untyped_empties_the_world`)는 무작위 활동 뒤 모든 untyped를 회수하고 retype된 오브젝트가 하나도 남지 않았는지 확인합니다. -- **파괴 테스트**: 아주 깊은 파생 체인과 깊게 중첩된 CNode를 작은 고정 스택에서 파괴하여, 파괴가 반복으로 이루어짐을 보입니다. + 또한 이 열이 종료, 태스크 해체, 메모리 재사용 경로를 충분히 밟았는지, 그리고 분할, 자식의 분할, 자식에서 만든 오브젝트, 자식 구간의 재사용을 충분히 밟았는지도 확인합니다. 두 번째 테스트(`revoking_every_untyped_empties_the_world`)는 무작위 활동 뒤 모든 untyped를 회수하고 retype된 오브젝트와 자식 untyped가 하나도 남지 않았는지 확인합니다. +- **파괴 테스트**: 아주 깊은 파생 체인, 깊게 중첩된 CNode, 60,000단계로 중첩된 자식 untyped 체인을 작은 고정 스택에서 파괴하여, 파괴가 반복으로 이루어짐을 보입니다. - **부팅 자가 테스트**: 루트 태스크가 격리된 태스크들을 만듭니다. 각 태스크는 자기 CNode와, 이미지 텍스트와 읽기 전용 데이터만 매핑된 자기 주소 공간을 가집니다. 다음을 확인합니다. - 루트 태스크의 슬롯 번호가 격리된 CNode에서는 아무 의미도 없는지 - 루트만 가진 주소를 읽으면 정확히 그 주소에서 폴트가 나는지 @@ -331,6 +408,16 @@ untyped를 회수하면 거기서 잘라낸 것이 전부 종료됩니다. 조 - 회수된 untyped 메모리가 다시 retype되는지(고갈될 때까지, 세 라운드, 매번 0으로 채워짐) 마커는 `tools/qemu-boot-test.sh`에 있습니다. 이 스크립트는 `k0: task fault` 줄의 정확한 개수와 `k0: unknown syscall` 줄이 정확히 하나일 것도 요구합니다. 그래서 파괴된 뒤에 재개되거나 엉뚱한 이유로 죽는 태스크가 있으면 테스트가 실패합니다. +- **분할 자가 테스트**: `userspace/root-task/src/main.rs`의 `test_split`은 모든 이미지에서 실행되며 `root: timeout tests pass` 뒤, `root: revocation tests pass` 앞에 `root: untyped split tests pass`를 출력합니다. 다음을 확인합니다. + - 거부마다 정해진 에러 코드가 반환되고 목적지 슬롯에 케이퍼빌리티가 남지 않는지 + - 자식을 복사할 수도 매핑할 수도 없는지 + - 24 그래뉼짜리 슬랩에서 만든 태스크가, 슬랩에서 다시 잘라 자기 CNode로 옮겨 받은 8 그래뉼짜리 예산에서 오브젝트를 정확히 8개 얻는지. 이 태스크는 자기 예산을 회수하면 메모리가 예산으로 돌아오는지, 예산 전부를 자식 하나에 주고 그 자식을 다시 분할할 수 있는지도 안에서 확인합니다 + - 태스크가 예산을 다 쓰는 동안 슬랩의 나머지를 루트 태스크가 계속 쓸 수 있는지 + - 슬랩을 회수하면 태스크, 그 CNode, 주소 공간, 예산이 한 번의 호출로 제거되는지 + - 그 뒤 슬랩에서 다시 정확히 프레임 24개가 나오는지. 그중 넷은 매핑해서 그래뉼 전체를 읽으며 전부 0이어야 합니다. 마지막 단계 페이지 테이블, 태스크의 스택, TCB, 루트 태스크가 값을 써 둔 프레임이 있던 자리입니다 + - 슬랩을 삭제한 뒤에도 부모가 오브젝트를 만드는지 + + 태스크 실행과 회수는 같은 슬랩에서 두 번 진행하므로, 두 번째 라운드가 같은 메모리와 같은 슬롯을 다시 쓸 수 있음을 보여 줍니다. 16 KiB 이미지는 QEMU `-cpu max`에서 부팅해 부팅 검사를 통과하고, Apple 코어의 HVF에서도 부팅합니다. 기본 4 KiB 이미지는 CI의 부팅 매트릭스를 통과합니다. @@ -339,15 +426,17 @@ untyped를 회수하면 거기서 잘라낸 것이 전부 종료됩니다. 조 > [!NOTE] > 케이퍼빌리티 전송은 아직 없습니다. IPC로 케이퍼빌리티를 보낼 수 없고, 태스크가 케이퍼빌리티를 얻는 방법은 이미 가진 CNode 안으로 하는 `CAP_COPY`와 `CAP_MOVE`뿐입니다. 알림(notification)과 핸들러 태스크로의 폴트 전달도 아직 모델에 없고 코어는 하나입니다. 타임아웃은 있습니다([ipc_KR.md](ipc_KR.md) 참고). -- **가용성**: 격리되지 않습니다. 모든 태스크가 블록되어도 커널은 더 이상 멈추지 않고, 태스크는 타임아웃으로 자기 대기를 제한할 수 있으며, 커널 페이지 테이블과 주소 공간 등록부는 더 이상 소진될 수 없습니다. 타임아웃 없이 기다리는 태스크는 상대가 움직이지 않으면 여전히 영원히 기다릴 수 있으므로, 서버는 모든 대기에 타임아웃을 주어야 합니다. 우선순위와 CPU 예산은 없고, untyped 메모리를 가진 태스크는 태스크를 많이 만들어 다른 태스크의 몫을 희석시킬 수 있습니다. 커널은 선점되지 않으므로 `CAP_REVOKE` 같은 긴 시스템 콜은 모두를 지연시킵니다. 어드바이저리의 상태는 [SECURITY_KR.md](../../SECURITY_KR.md)의 GHSA-q99x-2wrv-358p를 참고하세요. +- **가용성**: 격리되지 않습니다. 모든 태스크가 블록되어도 커널은 더 이상 멈추지 않고, 태스크는 타임아웃으로 자기 대기를 제한할 수 있으며, 커널 페이지 테이블과 주소 공간 등록부는 더 이상 소진될 수 없습니다. 타임아웃 없이 기다리는 태스크는 상대가 움직이지 않으면 여전히 영원히 기다릴 수 있으므로, 서버는 모든 대기에 타임아웃을 주어야 합니다. 우선순위와 CPU 예산은 없고, untyped 메모리를 가진 태스크는 태스크를 많이 만들어 다른 태스크의 몫을 희석시킬 수 있습니다. 자식 untyped는 그런 태스크가 가진 메모리의 양을, 그래서 만들 수 있는 오브젝트의 수를 제한하지만 그 이상은 아닙니다. 커널은 선점되지 않으므로 `CAP_REVOKE` 같은 긴 시스템 콜은 모두를 지연시킵니다. 어드바이저리의 상태는 [SECURITY_KR.md](../../SECURITY_KR.md)의 GHSA-q99x-2wrv-358p를 참고하세요. - **줄 서 있던 송신자**: 엔드포인트에 이미 줄 서 있던 송신자는 자기 케이퍼빌리티가 회수된 뒤에도 메시지를 한 번 더 전달합니다. - **seL4와의 차이**: 다음과 같습니다. - 단일 레벨 CSpace입니다(가드나 다단계 조회 없음). - 케이퍼빌리티를 삭제하면 거기서 파생된 것도 함께 삭제됩니다. 오브젝트는 원본 케이퍼빌리티와 함께 죽습니다. - - 모든 오브젝트는 정확히 1 그래뉼이고 untyped는 쪼갤 수 없습니다. + - 모든 오브젝트는 정확히 1 그래뉼입니다. 더 작은 untyped는 `RETYPE`이 아니라 별도의 호출 `UNTYPED_SPLIT`으로, 온전한 그래뉼 단위의 크기를 주어 잘라냅니다. - IPC를 통한 케이퍼빌리티 전송이 없습니다. - 하드웨어 ASID를 사용하지 않으며, TTBR0 교체와 모든 해제, 테이블 분리, 주소 공간 파괴는 TLB 전체를 비웁니다. - **제어 케이퍼빌리티**: 전부 아니면 전무입니다. `Tcb`, `CNode`, `AddrSpace` 케이퍼빌리티는 권한을 갖지 않으므로 권한을 줄인 복사본을 만들 수 없습니다. 이런 케이퍼빌리티를 쥔 쪽은 그 오브젝트를 완전히 통제하며, 어떤 태스크의 TCB나 CNode, 주소 공간의 케이퍼빌리티를 쥔 쪽이 그 태스크를 통제합니다. `PartCtl`도 전부 아니면 전무입니다. 케이퍼빌리티 하나가 표와 모든 태스크의 도메인을 다루며, 표를 정하는 부분과 태스크를 배치하는 부분으로 나눌 수 없습니다. - **부팅 이후 새 코드**: 올릴 수 없습니다. 케이퍼빌리티 권한으로 보장하는 W^X 때문에 실행 가능한 메모리는 루트 태스크 이미지에만 있습니다. -- **회수 중 인터럽트**: 마스크됩니다. `CAP_REVOKE`와 `CAP_DELETE`의 시간은 제거되는 케이퍼빌리티 수에 비례합니다. +- **회수 중 인터럽트**: 마스크됩니다. `CAP_REVOKE`와 `CAP_DELETE`의 시간은 제거되는 케이퍼빌리티 수에 비례합니다. `UNTYPED_SPLIT`은 이것을 바꾸지 않습니다. 자식 untyped는 메모리를 제한할 뿐 회수의 시간을 제한하지 않으며, 중간에 끊었다가 이어서 할 수 있는 회수는 아직 없습니다. +- **자식 untyped는 고정**: 늘리거나 줄일 수 없고 부모에 다시 합칠 수도 없습니다. 삭제한 자식의 구간은 부모에서 파생된 것이 하나도 남지 않았을 때에만 부모에게 돌아옵니다. +- **회수는 지우지 않음**: `CAP_REVOKE`나 `CAP_DELETE`로 풀려난 메모리는 `RETYPE`이 그것으로 다시 오브젝트를 만들 때까지 0으로 채워지지 않습니다. 풀려난 구간을 지워야 하는 태스크는 그 구간의 그래뉼을 전부 retype해야 합니다. - **여기서 검증하지 못한 것**: 3단계 전부입니다. 실제 보드, KVM, Firecracker, Cloud Hypervisor, crosvm, 16550 콘솔 드라이버(실행한 적 없음), 하드웨어의 실제 보안 확장이 있는 GIC, `HCR_EL2.E2H`가 1로 고정된 CPU(이 경로는 Linux를 따랐고 어디에서도 실행하지 않았습니다)가 해당합니다. 1단계(`tools/boot-matrix.sh`, CI와 로컬에서 실행)와 2단계(2026-11-11과 2026-11-12에 손으로, Apple M5 Pro, QEMU HVF)가 지원 범위입니다. UEFI 행은 [uefi_KR.md](uefi_KR.md)에 있습니다. diff --git a/design/kr/exceptions_KR.md b/design/kr/exceptions_KR.md index 0fcb2ae..649e8a1 100644 --- a/design/kr/exceptions_KR.md +++ b/design/kr/exceptions_KR.md @@ -105,6 +105,10 @@ FP/SIMD 레지스터는 컨텍스트에 포함되지 않습니다. EL0의 모든 | 16 | `CONSOLE_READ` | 콘솔 입력 바이트 하나를 읽음(`console-input`으로 빌드한 이미지에만 있음, 아래 참고). 읽기 권리가 있는 `Console` 케이퍼빌리티가 필요 | | 17 | `PART_SET_TABLE` | 시간 분할 표를 정함. `PartCtl` 케이퍼빌리티가 필요([scheduling_KR.md](scheduling_KR.md#제어-케이퍼빌리티와-두-시스템-콜) 참고) | | 18 | `PART_SET_DOMAIN` | 아직 실행된 적 없는 태스크를 시간 분할 도메인에 넣음. `PartCtl` 케이퍼빌리티가 필요 | +| 19 | `UNTYPED_SPLIT` | untyped 케이퍼빌리티에서 주어진 그래뉼 수만큼의 더 작은 untyped 케이퍼빌리티를 잘라, 호출자가 지정한 목적지 슬롯에 넣음([capabilities_KR.md](capabilities_KR.md#untyped-분할) 참고) | +| 20 | `TCB_STATUS` | 태스크가 시작 전인지, 살아 있는지, 끝났는지 물음. `Tcb` 케이퍼빌리티가 필요하고 아무것도 바꾸지 않음([scheduling_KR.md](scheduling_KR.md#태스크가-끝났는지-묻기) 참고) | + +`TCB_STATUS`는 성공한 결과가 `x0`에서 항상 0은 아닌 유일한 호출입니다. 세 가지 답으로 0, 1, 2를 반환하고, 음수는 여전히 에러입니다. > [!IMPORTANT] > 알 수 없는 번호는 단순한 오류 코드로 끝나지 않습니다. K0는 이를 태스크가 손상되었거나 악의적이라는 신호로 보고, `k0: unknown syscall N, killing task`를 출력한 뒤 호출자를 종료합니다. @@ -121,6 +125,8 @@ k0: task fault dabort-lower (esr 0x92000046 elr 0x400398 far 0x0), killing task 그런 다음 `kill_current`를 호출합니다. 이 함수는 [scheduling_KR.md](scheduling_KR.md#정리)에서 설명하는 정리를 실행합니다. 태스크를 속해 있던 큐에서 제거하고, 응답 링크를 양쪽 모두 끊고, 태스크를 `Dead`로 표시합니다. 응답 링크를 끊으므로 이 태스크의 응답을 기다리던 태스크는 `NO_REPLY`와 함께 깨어납니다([ipc_KR.md](ipc_KR.md) 참고). `EXIT`와 알 수 없는 시스템 콜도 같은 경로를 사용합니다. +태스크가 이렇게 끝나도 다른 태스크에는 아무것도 보내지 않습니다. 죽은 태스크의 `Tcb` 케이퍼빌리티를 가진 태스크는 `TCB_STATUS`로 물어 `ENDED`를 받을 수 있지만 이유는 받지 못합니다([scheduling_KR.md](scheduling_KR.md#태스크가-끝났는지-묻기) 참고). + ### 종료 경로 모든 시스템 콜과 모든 폴트는 `finish`로 끝납니다. `finish`는 핸들러가 끝나고 케이퍼빌리티 정리가 전부 끝난 뒤에 실행됩니다. 핸들러는 폴트 없이도 호출한 태스크를 죽일 수 있습니다. `EXIT`, 자신의 CNode·주소 공간·TCB 삭제, 자신이 잘려 나온 untyped의 회수가 그렇습니다. 그래서 `finish`는 다른 모든 일이 끝난 뒤에야 컨텍스트를 어떻게 할지 정합니다. @@ -137,7 +143,7 @@ k0: task fault dabort-lower (esr 0x92000046 elr 0x400398 far 0x0), killing task | `k0: idle (waiting for a timeout)` | 기한을 가진 대기자가 하나 이상 있는 채로 커널이 처음 대기할 때 | | `k0: all tasks stopped (none ready, no timeout pending)` | 기한을 가진 대기자가 없는 채로 커널이 처음 대기할 때 | -두 번째 상태에서는 지금으로서는 태스크를 깨울 수단이 없습니다. 알림 오브젝트도, 콘솔 입력을 제외하면 태스크용 장치 인터럽트도 없기 때문입니다. 기계는 대기 상태로 남습니다. `console-input` 이미지에서는 콘솔 입력을 기다리는 태스크도 대기자로 셉니다. 기다릴 것이 콘솔 입력뿐이면 커널은 아무것도 출력하지 않으며, 이것이 터미널 이미지의 정상 상태입니다. 두 번째 줄은 기한이 있는 대기자도 콘솔 대기자도 없을 때만 출력됩니다. 루트 도메인이 아닌 도메인이 적힌 표가 정해져 있거나 보류 중인 동안에는 첫 번째 줄을 출력하지 않습니다. 그때 두 번째 줄은 어느 도메인에도 준비된 태스크와 기한이 있는 대기자가 없고 콘솔 입력을 기다리는 태스크도 없을 때만 출력합니다. `tools/qemu-boot-test.sh`는 `k0: all tasks`로 시작하는 줄이 나오면 실패로 판정합니다. +두 번째 상태에서는 지금으로서는 태스크를 깨울 수단이 없습니다. 알림 오브젝트도, 콘솔 입력을 제외하면 태스크용 장치 인터럽트도 없기 때문입니다. 기계는 대기 상태로 남습니다. `console-input` 이미지에서는 콘솔 입력을 기다리는 태스크도 대기자로 셉니다. 기다릴 것이 콘솔 입력뿐이면 커널은 아무것도 출력하지 않습니다. 서비스 중인 터미널 이미지에는 기한이 있는 대기자도 있습니다. 감독자의 폴과 폴 사이에 기다리는 루트 태스크입니다. 첫 번째 줄은 자가 테스트 중에 이미 한 번 출력됐으므로 이때도 아무것도 출력하지 않습니다. 두 번째 줄은 기한이 있는 대기자도 콘솔 대기자도 없을 때만 출력됩니다. 루트 도메인이 아닌 도메인이 적힌 표가 정해져 있거나 보류 중인 동안에는 첫 번째 줄을 출력하지 않습니다. 그때 두 번째 줄은 어느 도메인에도 준비된 태스크와 기한이 있는 대기자가 없고 콘솔 입력을 기다리는 태스크도 없을 때만 출력합니다. `tools/qemu-boot-test.sh`는 `k0: all tasks`로 시작하는 줄이 나오면 실패로 판정합니다. ### 복귀 검사 @@ -179,7 +185,7 @@ EL0에서 받은 IRQ는 시스템 콜과 같은 방식으로 저장됩니다. ## 알려진 공백 > [!NOTE] -> 폴트를 일으킨 태스크는 항상 종료됩니다. 페이저나 감독자가 대응할 수 있도록 폴트를 IPC로 핸들러 태스크에 전달하는 기능은 계획되어 있지만 아직 없습니다. +> 폴트를 일으킨 태스크는 항상 종료됩니다. 페이저나 감독자가 대응할 수 있도록 폴트를 IPC로 핸들러 태스크에 전달하는 기능은 계획되어 있지만 아직 없습니다. 지금 있는 것은 `TCB_STATUS`입니다. 태스크의 `Tcb` 케이퍼빌리티를 가진 쪽이 그 태스크가 끝났는지 물을 수 있고, 언제 왜 끝났는지는 알 수 없습니다. - 인터럽트를 제외한 **EL1의 모든 예외는 치명적**입니다. 커널은 자신의 폴트를 복구하지 않습니다. fatal 벡터 경로가 진단을 출력하고 시스템 전체를 정지시킵니다. 커널 자신의 검사가 찾아낸 불변식 위반도 `k0_arch::fatal`을 거쳐 같은 방식으로 정지합니다. - 폴트를 일으키거나 알 수 없는 시스템 콜을 호출한 태스크는 자기만 죽습니다. 그 뒤 준비된 태스크가 없으면 커널은 멈추지 않고 대기합니다([종료 경로](#종료-경로) 참고). 타임아웃 없이 기다리는 태스크는 상대가 동작하지 않으면 계속 기다릴 수 있고, 스케줄러에는 우선순위도 CPU 예산도 없습니다(GHSA-q99x-2wrv-358p는 여전히 0.1.0 이하에 영향을 주는 것으로 게시되어 있음). 격리는 가용성을 다루지 않습니다. diff --git a/design/kr/ipc_KR.md b/design/kr/ipc_KR.md index 83ca1ff..33cd64b 100644 --- a/design/kr/ipc_KR.md +++ b/design/kr/ipc_KR.md @@ -159,7 +159,7 @@ TCB에는 `deadline`, `tnext`, `tprev` 필드가 있습니다. `k0-sched`는 기 - `k0: idle (waiting for a timeout)`: 기한이 있는 대기자가 하나 이상 있으므로 태스크를 깨울 것이 있습니다. - `k0: all tasks stopped (none ready, no timeout pending)`: 기한이 있는 대기자도 콘솔 입력을 기다리는 태스크도 없습니다. 지금은 Notification 오브젝트가 없고 태스크를 깨우는 장치 인터럽트는 콘솔 입력뿐이므로 이 상태에서는 어떤 것도 태스크를 깨울 수 없고, 머신은 idle 상태로 남습니다. `tools/qemu-boot-test.sh`는 `k0: all tasks`로 시작하는 줄을 모두 실패로 처리합니다. -기다릴 것이 콘솔 입력뿐이면 커널은 어느 줄도 출력하지 않습니다. 터미널 이미지에서는 이것이 정상 상태입니다. 루트 도메인이 아닌 도메인이 적힌 시간 분할 표가 정해져 있거나 보류 중인 동안에는 첫째 줄을 출력하지 않습니다. 둘째 줄은 어느 도메인에도 준비된 태스크와 기한이 있는 대기자가 없고 입력을 기다리는 태스크도 없을 때만 출력합니다([scheduling_KR.md](scheduling_KR.md#실행할-태스크가-없을-때) 참고). +기다릴 것이 콘솔 입력뿐이면 커널은 어느 줄도 출력하지 않습니다. 서비스 중인 터미널 이미지도 어느 줄도 출력하지 않습니다. 루트 태스크가 감독자의 폴과 폴 사이에 타임아웃을 걸고 기다리고, 첫째 줄은 자가 테스트 중에 이미 한 번 출력됐기 때문입니다([terminal_KR.md](terminal_KR.md#감독) 참고). 루트 도메인이 아닌 도메인이 적힌 시간 분할 표가 정해져 있거나 보류 중인 동안에는 첫째 줄을 출력하지 않습니다. 둘째 줄은 어느 도메인에도 준비된 태스크와 기한이 있는 대기자가 없고 입력을 기다리는 태스크도 없을 때만 출력합니다([scheduling_KR.md](scheduling_KR.md#실행할-태스크가-없을-때) 참고). > [!WARNING] > 모든 태스크가 블록되어도 커널은 더 이상 정지하지 않으며, 태스크는 타임아웃으로 자신의 대기에 상한을 걸 수 있습니다. 그래도 가용성은 보호되지 않습니다. 타임아웃 없이 기다리는 태스크는 상대방이 동작하지 않으면 영원히 기다릴 수 있고, 엔드포인트 케이퍼빌리티를 가진 격리 태스크는 여전히 다른 태스크를 기다리게 만들 수 있습니다. 이것이 [SECURITY_KR.md](../../SECURITY_KR.md)의 어드바이저리 GHSA-q99x-2wrv-358p의 주제입니다. 어드바이저리는 릴리즈 시점에 갱신합니다. diff --git a/design/kr/scheduling_KR.md b/design/kr/scheduling_KR.md index 41cc771..6a216db 100644 --- a/design/kr/scheduling_KR.md +++ b/design/kr/scheduling_KR.md @@ -21,7 +21,7 @@ - `crates/k0-sched/src/lib.rs`(`Core`를 둘러싼 큐와 설치된 태스크) - `crates/k0-arch/src/irq.rs`의 타이머 - `crates/k0-ipc/src/lib.rs`의 `teardown` -- `kernel/src/syscall.rs`의 `sys_tcb_configure`, `sys_tcb_resume`, `sys_part_set_table`, `sys_part_set_domain`, `k0_preempt`, `k0_leave`, `wait_for_work`, `kill_current`, `finish` +- `kernel/src/syscall.rs`의 `sys_tcb_configure`, `sys_tcb_resume`, `sys_tcb_status`, `sys_part_set_table`, `sys_part_set_domain`, `k0_preempt`, `k0_leave`, `wait_for_work`, `kill_current`, `finish` 이 문서는 현재 `main` 브랜치(미배포)를 기준으로 합니다. @@ -319,6 +319,33 @@ n번 틱은 `T0 + n * P`에 옵니다. `T0`는 부팅 때 타이머를 설정하 죽은 태스크의 프레임은 정리가 해제하지 않습니다. 프레임은 `Dead` TCB로 남고, `TCB_CONFIGURE`와 `TCB_RESUME`이 이를 거부하므로 죽은 태스크는 다시 시작되지 않습니다. 그 메모리는 TCB의 원본 케이퍼빌리티를 삭제하거나 그것이 나온 untyped를 회수한 뒤, untyped를 다시 retype할 때 재사용되며 그때 프레임은 다시 0으로 지워집니다. 단순히 종료만 한 태스크는 그때까지 묶인 케이퍼빌리티 두 개를 유지합니다. +## 태스크가 끝났는지 묻기 + +`TCB_STATUS`는 시스템 콜 20번입니다. `Tcb` 케이퍼빌리티를 가진 쪽에게 그 태스크가 시작됐는지, 끝났는지를 알려 줍니다. `x0`은 호출자 CNode 안에서 `Tcb` 케이퍼빌리티가 든 슬롯입니다. 결과는 `x0`으로 돌아오고, 다음 표와 같이 태스크의 상태만으로 정해집니다. + +| 결과 | 값 | 태스크 상태 | +| --- | --- | --- | +| `NOT_STARTED` | 0 | `Inactive` 또는 `Stopped`. 구성되지 않았거나, 구성됐지만 재개된 적이 없음 | +| `ALIVE` | 1 | `Ready`, `Running`, 또는 블록된 상태 가운데 하나(`BlockedSend`, `BlockedRecv`, `BlockedCall`, `BlockedReply`, `BlockedConsole`) | +| `ENDED` | 2 | `Dead`. 태스크가 종료했거나, 폴트를 냈거나, 알 수 없는 시스템 콜을 했거나, 정리됨 | + +음수 결과는 에러입니다. `BAD_SLOT`은 슬롯 번호가 0이거나 범위 밖이거나 슬롯이 비어 있다는 뜻입니다. `BAD_CAP`은 슬롯에 다른 종류의 케이퍼빌리티가 들어 있다는 뜻입니다. 다른 시스템 콜은 모두 성공하면 0을 반환하므로, 성공한 결과가 `x0`에서 0이 아닐 수 있는 호출은 이것뿐입니다. 값은 `crates/k0-abi/src/lib.rs`의 `tcb_status` 모듈에 있습니다. + +이 호출의 성질은 다음과 같습니다. + +- **아무것도 바꾸지 않음**: TCB의 상태 필드를 읽을 뿐 아무것도 쓰지 않습니다. 성공한 호출도 거부된 호출도 슬롯, TCB, 큐, 스케줄러를 그대로 둡니다. +- **이유를 알리지 않음**: 태스크가 왜 끝났는지는 알려 주지 않습니다. 종료 코드와 끝나는 방식은 끝나는 태스크가 고르는 값이므로, 커널은 이를 판단의 근거로 내놓지 않습니다. 블록된 상태들도 서로 구분해 주지 않습니다. +- **한 번도 실행되지 않은 태스크**: 처음 실행되기 전에 정리된 태스크도 `ENDED`입니다. +- **답은 바뀌지 않음**: `Dead`는 마지막 상태입니다. 정리는 `Dead` 태스크에서 곧바로 돌아오고, `TCB_CONFIGURE`는 `Inactive`만, `TCB_RESUME`은 `Stopped`만 받기 때문입니다. 그래서 이따금 묻는 쪽도 태스크가 끝난 것을 놓칠 수 없습니다. `Tcb` 케이퍼빌리티가 있는 동안 답은 계속 `ENDED`입니다. 그 케이퍼빌리티가 삭제되면 슬롯이 비므로 답은 `BAD_SLOT`입니다. +- **물을 수 있는 쪽**: `Tcb` 케이퍼빌리티에는 권한이 없으므로 그것을 가진 쪽은 누구나 물을 수 있습니다. 태스크는 자기 자신에 대해서도 물을 수 있고 `ALIVE`를 받습니다. +- **물을 때만**: 태스크가 끝나도 커널은 아무것도 보내지 않습니다. 알림이 없고, 폴트를 핸들러 태스크에 전달하지도 않습니다([exceptions_KR.md](exceptions_KR.md) 참고). 알고 싶은 쪽이 묻고, 또 물어야 합니다. +- **모든 이미지에 있음**: 이 호출에는 feature가 필요 없습니다. + +> [!NOTE] +> 커널은 태스크가 끝났다는 것을 스스로 누구에게도 알리지 않습니다. `Tcb` 케이퍼빌리티를 가진 쪽이 물어야 하며, 이유는 알 수 없고 끝나지 않은 채 멈춰 있는 태스크에 대해서도 알 수 없습니다. + +터미널 이미지의 루트 태스크는 이 호출로 터미널과 볼트를 감독합니다([terminal_KR.md](terminal_KR.md#감독) 참고). + ## 실행할 태스크가 없을 때 실행할 태스크가 없어도 커널은 더 이상 코어를 파킹하지 않습니다. `kernel/src/syscall.rs`의 `wait_for_work`가 다음 세 경우에 넘겨받습니다. @@ -338,7 +365,7 @@ n번 틱은 `T0 + n * P`에 옵니다. `T0`는 부팅 때 타이머를 설정하 - `k0: idle (waiting for a timeout)`: 기한이 있는 대기자가 하나 이상 있습니다. - `k0: all tasks stopped (none ready, no timeout pending)`: 기한이 있는 대기자도 콘솔 입력을 기다리는 태스크도 없습니다. 지금은 Notification 오브젝트도, 콘솔 입력을 제외한 태스크용 장치 인터럽트도 없으므로 이 상태에서는 어떤 것도 태스크를 깨울 수 없고, 머신은 idle 상태로 남습니다. -기다릴 것이 콘솔 입력뿐이면(`console-input` 이미지) 커널은 아무것도 출력하지 않으며, 이것이 터미널 이미지의 정상 상태입니다. +기다릴 것이 콘솔 입력뿐이면(`console-input` 이미지) 커널은 아무것도 출력하지 않습니다. 서비스 중인 터미널 이미지가 조용한 이유는 따로 있습니다. 루트 태스크가 감독자의 폴과 폴 사이에 타임아웃을 걸고 기다리므로([terminal_KR.md](terminal_KR.md#감독) 참고) 기한이 있는 대기자가 있고, 첫 번째 줄은 자가 테스트 중에 이미 한 번 출력됐기 때문입니다. 루트 도메인이 아닌 도메인이 적힌 표가 정해져 있거나 보류 중인 동안에는 빈 창에서 기다리는 것이 정상이므로 첫째 줄은 출력하지 않습니다. 둘째 줄은 그때도 한 번 출력합니다. 어느 도메인에도 준비된 태스크가 없고, 어느 도메인에도 기한이 있는 대기자가 없고, 콘솔 입력을 기다리는 태스크도 없을 때입니다. 어떤 표에도 없는 도메인의 준비된 태스크는 끝내 실행되지 않지만, 이 검사에서는 준비된 것으로 셉니다. @@ -353,13 +380,14 @@ EL0에서 받은 SError는 여전히 머신 전체를 정지시키며, `k0_arch: - 목표값까지 세고 종료하는 태스크를 만들고 기다림 - 구성되지 않은 태스크, 이미 재개한 태스크, 죽은 태스크의 재개를 거부 +- 태스크가 보일 수 있는 상태마다 `TCB_STATUS`로 물음([부팅 때의 상태 테스트](#부팅-때의-상태-테스트) 참고) - 슬라이스 테스트(`userspace/root-task/src/timeslice.rs`) 실행: 양보하지 않는 태스크가 여전히 타이머에 선점되는지, 그리고 양보나 블록으로 CPU를 받은 태스크가 처음 맞는 틱에 끊기지 않는지 확인 - 시간 분할 테스트(`userspace/root-task/src/partition.rs`) 실행([부팅 때의 시간 분할 테스트](#부팅-때의-시간-분할-테스트) 참고) - 스레드 포인터 레지스터가 태스크 사이에 새지 않는지 확인 - 자기 CNode와 자기 주소 공간을 가진 격리 태스크를 만들고, 루트 태스크의 슬롯 번호가 거기서 아무 의미가 없는지 확인 - 모든 상태(inactive, stopped, ready, send·receive·call에서 블록, 응답 대기, 응답 자격 보유, 엔드포인트 큐의 머리·중간·꼬리)의 태스크 삭제, 태스크가 줄 서 있는 엔드포인트 삭제, CNode 회수 또는 주소 공간 삭제로 태스크 종료, 태스크가 자기 TCB를 삭제하고 자신이 잘려 나온 untyped를 회수하는 경우 -`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: partition refusal pass`, `root: partition window pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: revocation tests pass`, `root: partition sealed`, `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: tcb status tests pass`, `root: slice test yield pass`, `root: slice test block pass`, `root: preempt test pass`, `root: partition refusal pass`, `root: partition window pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: revocation tests pass`, `root: partition sealed`, `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초를 더합니다. @@ -374,6 +402,16 @@ EL0에서 받은 SError는 여전히 머신 전체를 정지시키며, `k0_arch: 슬라이스 규칙을 넣은 상태로 QEMU에서 측정하니, 주기의 90 %에서 양보하는 공격 태스크 곁에서 다른 태스크가 CPU의 53.8 %부터 54.9 %를 가졌습니다(세 번 실행). 태스크 셋일 때는 어느 태스크도 29.7 % 아래로 내려가지 않았습니다. 양보 대신 틱 직전에 타임아웃 대기를 시작하는 공격 태스크 곁에서는 다른 태스크가 56.5 %를 가졌습니다. 모든 실행은 QEMU(TCG와 HVF)에서 했고 하드웨어에서는 실행하지 않았으며, 양보 지점은 공격 태스크를 위해 정했으므로 공격 태스크가 스스로 그 지점을 찾는 데 무엇이 필요한지는 측정하지 않았습니다. +### 부팅 때의 상태 테스트 + +`sys_tcb_status`는 커널 바이너리에 있고, 커널 바이너리에는 호스트 테스트가 없습니다. `k0-abi`의 호스트 테스트 하나는 세 결과 값이 서로 다르고 음수가 아니라는 것만 확인합니다. 호출 자체는 부팅할 때마다 루트 태스크가 확인합니다. 확인은 다른 자가 테스트에 이미 그 상태의 태스크가 있는 자리에 들어 있고, `root: tcb status tests pass` 줄은 `root: fault isolation tests pass` 뒤에 나옵니다. 일부 확인은 그 뒤의 테스트에서 실행됩니다. 확인하는 것은 다음과 같습니다. + +- **거부**: 슬롯 0, 범위 밖의 슬롯 번호, 빈 슬롯은 `BAD_SLOT`입니다. `Console` 케이퍼빌리티와 `Frame` 케이퍼빌리티는 `BAD_CAP`입니다. +- **시작 전**: 한 번도 구성되지 않은 TCB, 같은 TCB에 `TCB_CONFIGURE`가 거부된 뒤, 구성됐지만 아직 재개되지 않은 TCB입니다. +- **살아 있음**: 루트 태스크 자신, `TCB_RESUME` 직후의 태스크, `RECV`에서 기다리는 태스크, 응답을 기다리는 태스크입니다. +- **끝남**: `EXIT` 뒤의 태스크(두 번 묻고 답이 같음), 종료한 서버, 데이터 abort 뒤와 FP/SIMD 사용 뒤와 알 수 없는 시스템 콜 뒤의 태스크, CNode가 회수된 태스크, 주소 공간이 삭제된 태스크, 한 번도 실행되지 않고 정리된 태스크입니다. +- **삭제됨**: `Tcb` 케이퍼빌리티에 `CAP_DELETE`를 한 뒤의 답은 `BAD_SLOT`입니다. + ### 시간 분할 스케줄러의 호스트 테스트 크레이트 `k0-part`에는 호스트 테스트가 36개 있고, `tools/host-test.sh`가 실행합니다. @@ -390,7 +428,7 @@ EL0에서 받은 SError는 여전히 머신 전체를 정지시키며, `k0_arch: - **시계 산술**(9개): 따로 작성한 기준과 비교한 틱 번호, 설정한 시각의 직전과 바로 그 시각, 카운터 범위의 끝 근처 값, 주기 0, 그리고 틱 번호가 뒤로 가거나 되풀이되지 않는다는 것을 확인합니다. - **Lean 모델의 기록된 결과**(3개): [증명한 것](#증명한-것)을 참고하세요. -`k0-cap`에는 호스트 테스트가 54개 있습니다. 그 가운데 둘이 `PartCtl`에 관한 것입니다. 마스크와 배지가 무엇이든 복사본을 만들 수 없다는 것, 그리고 다른 값이 함께 든 `PartCtl` 워드는 디코드되지 않는다는 것입니다. +`k0-cap`에는 호스트 테스트가 71개 있습니다. 그 가운데 둘이 `PartCtl`에 관한 것입니다. 마스크와 배지가 무엇이든 복사본을 만들 수 없다는 것, 그리고 다른 값이 함께 든 `PartCtl` 워드는 디코드되지 않는다는 것입니다. `k0-sched`, `k0-ipc`, 커널 바이너리에는 호스트 테스트가 없습니다. 이들이 `Core`에 더하는 것(큐, 기한 목록, 타이머 호출)은 부팅 테스트와 리뷰로 확인합니다. @@ -451,4 +489,5 @@ EL0에서 받은 SError는 여전히 머신 전체를 정지시키며, `k0_arch: - **블록된 태스크**: IPC 상대가 동작하거나, 기한이 지나거나, 엔드포인트가 삭제되면 깨어납니다. - **죽은 TCB**: 정리가 회수하지 않습니다. 프레임은 케이퍼빌리티를 삭제하거나 untyped를 회수한 뒤 다시 retype할 때만 재사용됩니다. - **주소 공간 식별자**: 하드웨어 주소 공간 식별자를 사용하지 않으므로 주소 공간 사이의 전환마다 TLB 전체를 비웁니다. -- **죽은 태스크**: 다시 시작할 수 없습니다. 새 태스크에는 새 TCB가 필요합니다. +- **죽은 태스크**: 다시 시작할 수 없습니다. 새 태스크에는 새 TCB가 필요합니다. 터미널 이미지의 감독자가 하는 일이 바로 이것입니다. 끝난 서비스에서 남은 것을 제거하고 같은 메모리와 같은 슬롯에 새 태스크를 만듭니다([terminal_KR.md](terminal_KR.md#감독) 참고). +- **태스크가 끝나도 알림이 없음**: 커널은 어떤 태스크가 끝났다는 것을 다른 태스크에 알리지 않습니다. `Tcb` 케이퍼빌리티를 가진 쪽이 `TCB_STATUS`로 물을 수 있으므로 감독자는 폴을 해야 합니다. 이유는 알 수 없고, 끝나지 않은 채 멈춰 있는 태스크는 `ALIVE`로 보입니다. diff --git a/design/kr/terminal_KR.md b/design/kr/terminal_KR.md index d40a7a3..2465d42 100644 --- a/design/kr/terminal_KR.md +++ b/design/kr/terminal_KR.md @@ -6,7 +6,7 @@ -이 노트는 사람이 시리얼 선으로 K0와 대화하는 방법을 설명합니다. 커널이 콘솔 UART에서 바이트를 받고, 시스템 콜 `CONSOLE_READ`로 태스크 하나, 즉 **터미널**에 넘겨 줍니다. 터미널은 볼트의 운영자입니다([vault_KR.md](vault_KR.md) 참고). 볼트의 상태를 보여 주고, 키를 만들고, 키를 지웁니다. 코드는 `crates/k0-conin`(수신 로직), `kernel/src/syscall.rs`(`CONSOLE_READ`), `userspace/k0-term`(터미널), `userspace/root-task/src/service.rs`(연결과 점검)에 있습니다. +이 노트는 사람이 시리얼 선으로 K0와 대화하는 방법을 설명합니다. 커널이 콘솔 UART에서 바이트를 받고, 시스템 콜 `CONSOLE_READ`로 태스크 하나, 즉 **터미널**에 넘겨 줍니다. 터미널은 볼트의 운영자입니다([vault_KR.md](vault_KR.md) 참고). 볼트의 상태를 보여 주고, 키를 만들고, 키를 지웁니다. 코드는 `crates/k0-conin`(수신 로직), `kernel/src/syscall.rs`(`CONSOLE_READ`), `userspace/k0-term`(터미널), `userspace/k0-sup`(터미널과 볼트를 감독하는 정책), `userspace/root-task/src/service.rs`(연결, 점검, 감독자의 루프)에 있습니다. > [!NOTE] > 입력과 터미널은 선택 사항이며 기본값은 꺼짐입니다. `console-input` 없이 빌드한 이미지에는 수신 코드도, `CONSOLE_READ`도, 이 노트의 로그 줄도 없습니다. `terminal` 없이 빌드한 이미지에는 터미널 코드가 없습니다. @@ -83,17 +83,20 @@ QEMU는 시리얼 포트를 사용자의 터미널에 연결합니다. `cargo ru - **읽는 쪽의 창에서만**: 시간 분할 표가 있을 때 바이트는 읽는 쪽의 도메인이 도는 동안에만 전달됩니다. 그렇지 않으면 그 도메인이 도는 다음 틱까지 링에서 기다립니다([scheduling_KR.md](scheduling_KR.md#표가-있을-때의-콘솔-입력) 참고). 터미널 이미지는 도메인 하나로 실행되므로 지금은 터미널 이미지에 해당하지 않습니다. - **케이퍼빌리티 변경으로 깨우기**: 케이퍼빌리티가 삭제, 회수 또는 이동된 대기자는 즉시 `REVOKED`로 깨어납니다. - **타임아웃으로 깨우기**: 플래그에 타임아웃을 준 읽기는 그 시간이 다 되면 깨어납니다(타임아웃은 [scheduling_KR.md](scheduling_KR.md) 참고). -- **조용한 유휴**: 기다릴 것이 콘솔 입력뿐이면 커널은 아무것도 출력하지 않습니다. 이것이 터미널 이미지의 정상 상태입니다. `k0: all tasks stopped (none ready, no timeout pending)`는 시간 제한이 있는 대기자도, 콘솔 대기자도 없을 때만 출력됩니다. +- **조용한 유휴**: 기다릴 것이 콘솔 입력뿐이면 커널은 아무것도 출력하지 않습니다. `k0: all tasks stopped (none ready, no timeout pending)`는 시간 제한이 있는 대기자도, 콘솔 대기자도 없을 때만 출력됩니다. 서비스 중인 터미널 이미지에는 둘 다 있습니다. 터미널은 입력을 기다리고, 루트 태스크는 감독자의 폴과 폴 사이에 타임아웃을 걸고 기다립니다([감독](#감독) 참고). ## 터미널의 연결과 적대적 태스크 점검 터미널 이미지는 자가 테스트를 모두 먼저 실행합니다. 그다음 루트 태스크가 다음을 합니다. -1. 새 볼트를 시작하고(빌드에 포함된 경우) 부팅 시드를 건넵니다. 로그 줄은 `root: vault seeded`, 또는 `root: vault has no seed (boot seed has no entropy)`, 또는 `root: vault has no seed (no algorithm in this image)`입니다. -2. 터미널과 똑같이 연결한 적대적 태스크 둘을 실행합니다. 둘 다 거부되어야 하며 폴트로 끝나야 합니다. 줄은 `root: terminal console filter [...]`, `root: terminal wiring holds`, 그리고 `k0: task fault` 두 줄입니다. -3. 자신의 admin 케이퍼빌리티를 버리고, 터미널을 시작하고, 영원히 블록합니다. 줄은 `root: service started`이며 그다음 배너가 나옵니다. +1. 서비스마다 untyped 케이퍼빌리티에서 메모리 슬랩을 하나씩 잘라내고, 볼트가 빌드에 포함돼 있으면 두 서비스가 함께 쓰는 오브젝트를 만듭니다([감독](#감독) 참고). +2. 볼트가 빌드에 포함돼 있으면 시드를 받지 않는 볼트로 볼트의 재시작 경로를 시험합니다. 줄은 `root: vault restart test pass`입니다. +3. 새 볼트를 시작하고(빌드에 포함된 경우) 부팅 시드를 건넵니다. 로그 줄은 `root: vault seeded`, 또는 `root: vault has no seed (boot seed has no entropy)`, 또는 `root: vault has no seed (no algorithm in this image)`입니다. +4. 터미널과 똑같이 연결한 적대적 태스크 둘을, 터미널이 실행될 바로 그 자리에서 하나씩 차례로 실행합니다. 둘 다 거부되어야 하며 폴트로 끝나야 하고, 하나가 끝날 때마다 감독자의 코드가 그 태스크를 이루던 것을 전부 되찾습니다. 줄은 `root: terminal console filter [...]`, `root: terminal wiring holds`, `k0: task fault` 두 줄, 그리고 `root: terminal restart test pass`입니다. +5. 볼트가 살아 있고 적대적 태스크를 실행하기 전과 같은 상태인지 확인한 뒤, 자신의 admin 케이퍼빌리티를 버립니다. +6. `root: service started`를 출력하고 터미널을 시작하며, 그다음 배너가 나옵니다. 여기서부터 두 서비스를 감독합니다. -입력 경로가 없는 머신에서 루트 태스크는 `root: no console input, terminal not started`를 출력합니다. +입력 경로가 없는 머신에서 루트 태스크는 `root: no console input, terminal not started`를 출력하고, 서비스를 시작하지 않으며 아무것도 감독하지 않습니다. 터미널 태스크는 자체 주소 공간과 케이퍼빌리티 둘을 가집니다. @@ -107,6 +110,82 @@ QEMU는 시리얼 포트를 사용자의 터미널에 연결합니다. `cargo ru > [!WARNING] > 시리얼 선에는 인증이 없습니다. 선을 쥔 사람이 운영자이며, 키 삭제를 포함해 운영자의 연산 넷을 그대로 할 수 있습니다. 운영자는 서명할 수 없고, 시드를 전달할 수 없고, 정책을 바꿀 수 없습니다. +## 감독 + +터미널 이미지에서 루트 태스크는 터미널과 볼트를 감독합니다. `root: service started` 뒤에 영원히 블록하지 않습니다. 정해진 간격으로 두 태스크가 아직 살아 있는지 커널에 묻고, 끝난 서비스를 이루던 것을 전부 되찾고, 정해진 횟수 안에서 서비스를 다시 시작합니다. `terminal` 없이 빌드한 이미지에는 이것이 전혀 없습니다. + +

+ 루트 태스크는 두 번째 틱마다 TCB_STATUS로 터미널 태스크와 볼트 태스크가 끝났는지 커널에 묻습니다. 서비스마다 자리가 있습니다. 자리는 16 그래뉼짜리 슬랩과 루트 CNode의 고정된 슬롯 구간입니다. 태스크가 끝났으면 루트 태스크는 슬랩을 회수하고, 볼트라면 슬랩을 지우고, 기다린 뒤, 같은 슬랩과 같은 슬롯에 서비스를 다시 만듭니다. 부팅당 3번 다시 시작한 뒤에는 서비스가 내려간 채로 남습니다. +

+ +정책은 크레이트 `userspace/k0-sup`입니다. `no_std`이고, `unsafe` 코드를 금지하며, 의존성이 없고, 시스템 콜을 하지 않습니다. 바깥과는 트레이트 `Host`로만 이어지며, 이 트레이트에는 함수가 다섯 개 있습니다. 서비스가 끝났는지 묻기, 콘솔 입력 경로가 있는지 묻기, 서비스 걷어 내기, 서비스 다시 만들기, 줄 하나 출력하기입니다. 루트 태스크는 `userspace/root-task/src/service.rs`에서 시스템 콜로 `Host`를 구현하고, 호스트 테스트는 모형으로 구현합니다. 서비스 중의 루프와 부팅 때의 자가 테스트는 같은 함수 `Supervisor::poll`을 호출합니다. + +### 자리 + +서비스마다 **자리**(seat)가 하나 있습니다. 자리는 다음 두 가지입니다. + +- **슬랩**: 루트 태스크가 `UNTYPED_SPLIT`으로 잘라낸 16 그래뉼짜리 자식 untyped입니다([capabilities_KR.md](capabilities_KR.md#untyped-분할) 참고). 서비스의 주소 공간과 페이지 테이블, 스택, CNode, TCB가 모두 슬랩에서 나옵니다. 4 KiB 그래뉼에서는 14 그래뉼, 16 KiB 그래뉼에서는 8 그래뉼입니다. +- **루트 CNode의 슬롯 구간**: 자리의 첫 빌드가 구간을 정하고, 그 뒤의 빌드는 모두 같은 슬롯을 사용합니다. 정확히 구간의 끝에서 끝나지 않는 빌드는 루트 태스크의 점검에 실패합니다. + +그래서 다시 만들기는 몇 번을 하든 같은 메모리와 같은 슬롯을 사용합니다. 슬랩은 루트 태스크의 CNode에 남아 있습니다. 어느 서비스도 untyped 케이퍼빌리티를 받지 않습니다. + +볼트가 있는 이미지에서는 서비스가 쓰는 오브젝트 셋이 슬랩 밖에 있습니다. 볼트 엔드포인트, 운영자 응답 프레임, admin 요청 프레임입니다. 그래서 한 서비스를 다시 만들어도 다른 서비스의 주소 공간이 바뀌지 않고, 볼트를 다시 만들어도 터미널이 가진 볼트 엔드포인트 송신 케이퍼빌리티가 그대로 유효합니다. + +### 폴 + +루트 태스크는 자기만 가진 엔드포인트에서 기다립니다. 그 엔드포인트에는 메시지가 오지 않으므로 대기는 `TIMEOUT`으로만 끝납니다. 타임아웃으로 1틱을 요청하는데, 이 타임아웃은 호출 뒤 두 번째 틱에 끝나므로 두 번째 틱마다 폴(poll, 한 번 묻는 것)이 한 번 있습니다. 루트 태스크는 서비스가 가진 것에서는 기다리지 않으므로 서비스가 루트 태스크를 붙잡아 둘 수 없습니다. + +폴마다 감독자는 올라와 있는 서비스 각각에 대해 `TCB_STATUS`로 묻습니다([scheduling_KR.md](scheduling_KR.md#태스크가-끝났는지-묻기) 참고). 터미널이 먼저입니다. 태스크가 `ENDED`인 서비스는 다시 시작할지와 상관없이 같은 폴에서 **걷어 냅니다**. + +1. 루트 태스크가 슬랩을 회수합니다. 태스크, 그 CNode, 주소 공간, 페이지 테이블, 스택이 한 번의 호출로 제거되며, 그 뒤 `Tcb` 슬롯은 비어 있어야 합니다. +2. 볼트라면 슬랩을 지웁니다([vault_KR.md](vault_KR.md#볼트가-끝날-때) 참고). +3. 자리의 슬롯을 비웁니다. 거기 남아 있는 것은 이미지 프레임의 복사본이며, 이것은 슬랩에서 나온 것이 아닙니다. +4. 볼트가 있는 이미지에서는 함께 쓰는 프레임의 매핑을 해제합니다. 터미널이라면 운영자 응답 프레임의 읽기 전용 매핑입니다. 볼트라면 admin 요청 프레임의 매핑과 응답 프레임 자체이며, 그 뒤 루트 태스크가 응답 프레임을 0으로 채웁니다. 응답 프레임에는 마지막 공개 키가 남아 있을 수 있습니다. 응답 프레임은 볼트를 걷어 낼 때만 0으로 채우고, 터미널을 걷어 낼 때는 채우지 않습니다. + +그다음 정책이 그 자리를 어떻게 할지 정합니다. + +- **재시작 한도**: 서비스마다 부팅당 최대 3번 다시 시작합니다. 두 서비스의 한도는 따로이고, 한도는 다시 채워지지 않습니다. 횟수는 다시 시작하기로 정한 때에 세며, 성공한 때에 세지 않습니다. +- **대기**: 서비스를 다시 만드는 때는, 끝난 것을 본 폴을 기준으로 재시작 1은 그 뒤 첫 번째 폴, 재시작 2는 네 번째 폴, 재시작 3은 열여섯 번째 폴입니다. 적어도 2, 8, 32틱이고, 한 틱은 1초입니다. +- **이유를 쓰지 않음**: 정책은 태스크가 왜 끝났는지를 사용하지 않습니다. `TCB_STATUS`는 이유를 알려 주지 않고, 이유는 끝나는 태스크가 고르는 값이기 때문입니다. +- **입력 없는 터미널**: 이미지에 콘솔 입력 경로가 없으면, 곧 `NONBLOCK`을 준 `CONSOLE_READ`가 `NO_DEVICE`를 반환하면 터미널을 다시 시작하지 않습니다. 이때는 한도를 쓰지 않습니다. 루트 태스크는 터미널이 끝난 것을 보고 걷어 낸 뒤에만 묻고, 다시 만들기 직전에 한 번 더 묻습니다. 터미널이 올라와 있는 동안에는 묻지 않습니다. 이 질문이 링에서 바이트 하나를 가져갈 수 있기 때문입니다. +- **터미널 없는 볼트**: 서비스 중에 볼트를 호출하는 태스크는 터미널뿐입니다. 터미널이 완전히 내려가면(한도를 다 썼거나 입력 경로가 없음) 아직 올라와 있는 볼트는 같은 폴에서 멈추고 지우며, 다시 시작을 기다리던 볼트는 다시 만들지 않습니다. 사용할 태스크가 없는 키를 볼트의 메모리에 남기지 않으려는 것입니다. +- **끝**: 감독할 것이 남지 않으면 루트 태스크는 `root: supervision over`를 한 번 출력하고 타임아웃 없이 기다립니다. + +다시 시작한 터미널은 새 태스크입니다. 배너와 프롬프트를 다시 출력하고, 입력하던 줄은 사라집니다. 다시 시작한 볼트에는 키가 없습니다([vault_KR.md](vault_KR.md#볼트가-끝날-때) 참고). + +두 서비스가 모두 올라와 있는 동안 감독자는 아무것도 출력하지 않습니다. 출력하는 줄은 다음 표의 것이 전부입니다. ``는 1, 2, 3이고 ``은 2, 8, 32입니다. + +| 줄 | 의미 | +| --- | --- | +| `root: terminal ended, restart of 3 after at least ticks` | 터미널 태스크가 끝나서 걷어 냈음. 대기 뒤에 다시 만듦 | +| `root: vault ended and erased, restart of 3 after at least ticks` | 볼트 태스크가 끝나서 슬랩을 걷어 내고 지웠음. 대기 뒤에 다시 만듦 | +| `root: terminal started again` | 터미널을 자기 자리에 다시 만들었음 | +| `root: vault started again without a key` | 볼트를 자기 자리에 다시 만들었음. 시드도 키도 없음 | +| `root: terminal ended, no console input, not started again` | 터미널이 끝났고 콘솔 입력 경로가 없음 | +| `root: terminal ended, restart budget spent, not started again` | 터미널이 네 번째로 끝났음 | +| `root: vault ended and erased, restart budget spent, not started again` | 볼트가 네 번째로 끝났음 | +| `root: vault ended and erased, no terminal, not started again` | 볼트가 다시 시작을 기다리던 중에 터미널이 완전히 내려갔음 | +| `root: vault stopped and erased, no terminal` | 터미널이 완전히 내려갔을 때 볼트가 아직 올라와 있어서, 루트 태스크가 볼트를 멈추고 지웠음 | +| `root: supervision over` | 감독할 서비스가 남지 않았음 | + +`k0-sup`의 호스트 테스트 하나가 이 문구를 고정하고, 다른 하나는 어느 줄에도 `tools/qemu-boot-test.sh`가 실패로 읽는 낱말이 없는지 확인합니다. + +### 루트 태스크의 단계가 실패할 때 + +빌드와 걷어 내기의 모든 단계는 점검됩니다. 점검이 실패하면 루트 태스크는 자가 테스트에서처럼 `root: FAIL `을 출력하고 종료합니다. 볼트가 있는 이미지에서는 그 전에 볼트 슬랩을 지우기를 시도합니다. 슬랩을 회수하고, 16 그래뉼 전부를 프레임으로 retype하고, 17번째 `RETYPE`이 `EXHAUSTED`를 반환하기를 요구하고, 다시 회수합니다. 그런 다음 `root: vault erased before exit` 또는 `root: vault not erased`를 출력합니다. 이 동작은 서비스 볼트가 시드를 받기 직전부터 켜지므로, 적대적 태스크 실행 중에 실패한 점검도 포함합니다. 루트 태스크가 종료한 뒤에는 서비스를 감독하는 것이 없습니다. + +### 부팅 때의 재시작 경로 + +걷어 내기와 다시 만들기 코드는 터미널 이미지를 부팅할 때마다 서비스가 시작되기 전에 실행됩니다. 테스트용 한도(대기 없음, 재시작 한 번)로 실행하고 감독자의 줄은 꺼 둡니다. + +- **볼트**(볼트가 있는 이미지, `root: vault restart test pass`): 루트 태스크가 볼트의 자리에 볼트를 만들고 `fresh` 상태인지 확인합니다. 그 볼트의 CNode를 회수해 볼트를 끝내고, `TCB_STATUS`로 `ENDED`를 확인하고, 엔드포인트 호출이 수신자를 찾지 못하는지 확인합니다. 그다음 `Supervisor::poll` 한 번이 자리를 걷어 내고, 슬랩을 지우고, 볼트를 다시 만듭니다. 루트 태스크는 같은 슬롯에 다시 살아 있는 태스크가 있는지, 새 볼트가 `zeroized`를 보고하는지, 엔트로피가 충분하다고 적힌 시드를 주는 `INIT`을 거부하는지 확인합니다. 그런 다음 자리를 한 번 더 걷어 내서, 서비스 볼트가 같은 자리에서 처음부터 만들어지게 합니다. 이 테스트의 볼트는 비밀을 가진 적이 없고, 건네는 시드는 공개된 값입니다. +- **터미널**(`root: terminal restart test pass`): 적대적 태스크 둘이 터미널 자리의 처음 두 번의 시작입니다. 첫 번째가 폴트로 끝나면 폴 한 번이 자리를 걷어 내고 두 번째를 만듭니다. 두 번째가 폴트로 끝나면 폴 한 번이 자리를 걷어 내고 아무것도 만들지 않습니다. 재시작 한 번이라는 테스트용 한도를 다 썼기 때문입니다. 그 뒤 자리는 비어 있습니다. 자리의 세 번째 시작이 실제 터미널입니다. 이 테스트용 감독자에게는 볼트를 맡기지 않으므로, 테스트가 터미널 자리를 내려간 채로 두어도 서비스 볼트는 지워지지 않습니다. + +터미널과 볼트가 있는 이미지에서 `tools/qemu-boot-test.sh`는 다음 줄을 이 순서로 기대합니다. `root: vault restart test pass`, 시드에 관한 `root: vault ` 줄, `root: terminal console filter [`, `root: terminal wiring holds`, `k0: task fault dabort-lower` 두 줄, `root: terminal restart test pass`, `root: service started`입니다. 볼트가 없으면 처음 둘은 없습니다. 이미지별 폴트 줄 수는 바뀌지 않았습니다. + +> [!NOTE] +> 부팅 자가 테스트는 걷어 내기와 다시 만들기를 서비스마다 재시작 한 번으로, 대기 없이 실행합니다. 커밋된 테스트 가운데 서비스 중에 실제 터미널이나 실제 볼트를 끝내는 것은 없으므로, 실제 부팅의 시간이 걸린 루프는 머신에서 실행되지 않습니다("알려진 공백" 참고). + ## 화면과 명령 규칙 화면은 일반 텍스트입니다. 배너는 `K0 operator console, type 'help'`, 프롬프트는 `k0> `이고, 값은 `name=value`로 출력하며, 모든 명령은 정확히 한 줄 `ok` 또는 `err `으로 끝납니다. @@ -138,13 +217,24 @@ QEMU는 시리얼 포트를 사용자의 터미널에 연결합니다. `cargo ru ## 테스트 방법 -**호스트 테스트**(`tools/host-test.sh`): `k0-conin`은 가짜 UART로 19개, `k0-term`은 vault feature가 있으면 24개, 없으면 21개, `k0-vault`는 Ed25519가 있으면 20개, 없으면 11개입니다. 전체는 ARM 호스트에서 415개, 다른 호스트에서 327개입니다. +**호스트 테스트**(`tools/host-test.sh`): `k0-conin`은 가짜 UART로 19개, `k0-term`은 vault feature가 있으면 24개, 없으면 21개, `k0-vault`는 Ed25519가 있으면 22개, 없으면 13개, `k0-sup`은 20개입니다. 전체는 ARM 호스트에서 457개, 다른 호스트에서 369개입니다. + +`k0-sup`의 테스트 20개는 모든 호출을 기록하는 모형 호스트 위에서 감독자의 정책을 실행합니다. 다음을 확인합니다. + +- 올라와 있는 서비스는 그대로 두는지, 터미널이 올라와 있는 동안에는 입력 경로를 묻지 않는지 +- 끝난 서비스를 같은 폴에서 걷어 내고 대기 뒤에만 다시 만드는지, 대기가 재시작마다 길어지는지 +- 한도가 마지막 상태로 끝나는지, 두 서비스의 한도가 따로인지, 내려간 서비스가 모든 것을 무시하는지 +- 입력 경로가 없는 터미널이 한도를 쓰지 않고 내려가는지, 다시 만들기 직전에 입력 경로를 다시 묻는지 +- 끝난 볼트를 항상 걷어 내는지, 터미널이 완전히 내려가면 올라와 있는 볼트를 멈추는지, 그때 기다리던 볼트를 다시 만들지 않는지 +- `root: supervision over` 줄이 한 번만, 그리고 모든 것이 내려갔을 때만 나오는지 +- 서로 다른 한도 다섯 가지로 만든 무작위 이력 4000개에서 어느 서비스도 한도보다 많이 만들어지지 않고, 내려간 서비스가 내려간 채로 있고, 감독이 끝난 뒤에 다시 살아나지 않는지 +- 줄이 이 노트에 인용한 그대로인지, 어느 줄에도 부팅 테스트가 실패로 읽는 낱말이 없는지 **부팅 매트릭스**: 새 행은 `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에서 82행, CI에서 71행입니다. -**스크립트 세션**: `tools/term-test.py `는 QEMU의 시리얼 포트를 파이프에 연결해 이미지를 부팅하고 세션을 실행합니다. 모든 명령과 모든 오류, 지우기와 취소, CR LF, ESC 시퀀스, 너무 긴 줄, 키 생성, 공개 키 형식, zeroize, 줄 끝이 없는 200 kB, 연속 2000줄, 시리얼 브레이크, 브레이크 2000번의 폭주를 다룹니다. 폭주 단계는 입력 경로가 끊기지 않고 터미널이 다시 답하는지만 확인하며, 상한 자체는 호스트 테스트가 보입니다. 이 단계는 QEMU 8.0부터만 실행하므로 CI에서는 실행되지 않습니다. 그 전의 QEMU는 브레이크를 PL011 수신 FIFO에 넣을 때 깊이를 확인하지 않는데, 커널이 인터럽트를 마스크해 둔 동안 브레이크가 거기에 쌓이기 때문입니다. `tools/qemu-boot-test.sh`는 `K0_BOOT_INPUT=on|off`, `K0_BOOT_SERVICE=vault|plain|none`, 판정 전용 모드 `K0_BOOT_JUDGE`를 읽습니다. +**스크립트 세션**: `tools/term-test.py `는 QEMU의 시리얼 포트를 파이프에 연결해 이미지를 부팅하고 세션을 실행합니다. 모든 명령과 모든 오류, 지우기와 취소, CR LF, ESC 시퀀스, 너무 긴 줄, 키 생성, 공개 키 형식, zeroize, 줄 끝이 없는 200 kB, 연속 2000줄, 시리얼 브레이크, 브레이크 2000번의 폭주를 다룹니다. 폭주 단계는 입력 경로가 끊기지 않고 터미널이 다시 답하는지만 확인하며, 상한 자체는 호스트 테스트가 보입니다. 이 단계는 QEMU 8.0부터만 실행하므로 CI에서는 실행되지 않습니다. 그 전의 QEMU는 브레이크를 PL011 수신 FIFO에 넣을 때 깊이를 확인하지 않는데, 커널이 인터럽트를 마스크해 둔 동안 브레이크가 거기에 쌓이기 때문입니다. 스크립트는 프롬프트 뒤의 출력에 `root: `가 나타나도 세션을 실패로 처리합니다. 감독자는 서비스가 끝났을 때만 출력하므로, 정상 세션에서 이런 줄은 일어나지 않아야 할 재시작이 일어났다는 뜻입니다. 세션의 어느 단계도 서비스를 끝내지 않습니다. `tools/qemu-boot-test.sh`는 `K0_BOOT_INPUT=on|off`, `K0_BOOT_SERVICE=vault|plain|none`, 판정 전용 모드 `K0_BOOT_JUDGE`를 읽습니다. -**루트 태스크 자가 테스트**(`console-input`이 있는 이미지): `root: backspace without the input right [?]`와 `root: console input tests pass`입니다. 테스트 중에 바이트가 도착하면 둘째 줄은 `... pass (no input path)` 또는 `... cut short (the line is busy)`일 수도 있습니다. 터미널 이미지는 터미널이 없는 같은 이미지보다 `k0: task fault` 줄이 둘 더 나옵니다(볼트 없이 8줄, 볼트와 함께 10줄). +**루트 태스크 자가 테스트**(`console-input`이 있는 이미지): `root: backspace without the input right [?]`와 `root: console input tests pass`입니다. 테스트 중에 바이트가 도착하면 둘째 줄은 `... pass (no input path)` 또는 `... cut short (the line is busy)`일 수도 있습니다. 터미널 이미지는 터미널이 없는 같은 이미지보다 `k0: task fault` 줄이 둘 더 나옵니다(볼트 없이 8줄, 볼트와 함께 10줄). 서비스가 시작되기 전에 재시작 경로도 실행해 `root: terminal restart test pass`를 출력하고, 볼트가 빌드에 포함돼 있으면 `root: vault restart test pass`도 출력합니다([부팅 때의 재시작 경로](#부팅-때의-재시작-경로) 참고). ## 알려진 공백 @@ -162,6 +252,10 @@ QEMU는 시리얼 포트를 사용자의 터미널에 연결합니다. `cargo ru - **갈라진 화면 줄**: 운영자가 입력하는 동안 커널 줄이 나타나면 화면 줄은 갈라지지만 버퍼는 온전합니다. Enter는 버퍼 전체를 실행합니다. - **줄을 흉내 낼 수 있음**: `Console` 출력이 있는 태스크는 여전히 커널 또는 루트 태스크 줄처럼 보이는 줄을 출력할 수 있습니다. 접두어를 인증하는 것이 없기 때문입니다. 터미널은 추가로 현재 줄 안에서 지울 수 있습니다. - **서비스 모드에 서명 클라이언트 없음**: 키는 만들어 보여 주지만 다른 태스크가 아직 쓰지 않습니다. 클라이언트 서명은 자가 테스트가 보여 줍니다. -- **재시작 없음**: 터미널과 볼트는 죽어도 다시 시작되지 않습니다. 루트 태스크는 신뢰합니다. +- **감독은 신뢰 대상인 태스크의 폴**: 루트 태스크는 신뢰 대상이고, 루트 태스크를 감독하는 것은 없습니다. 서비스가 끝난 것은 다음 폴에서, 곧 최대 두 틱 뒤에 알게 되며, 그때도 CPU를 받아야 합니다. 끝나지 않은 채 멈춰 있는 서비스는 살아 있는 것으로 보여 알아채지 못합니다. 커널은 여전히 폴트를 핸들러 태스크에 전달하지 않습니다. +- **부팅당 재시작 3번**: 서비스를 세 번 다시 시작한 뒤이거나 입력 경로가 없는 머신에서 터미널이 끝나면, 그 서비스는 다음 부팅까지 내려가 있습니다. 터미널이 내려간 채로 남으면 볼트도 멈추고 지웁니다. +- **볼트를 다시 시작하면 키 없음**: 다시 시작한 볼트에는 시드도 키도 없고, 어느 것도 받지 않습니다([vault_KR.md](vault_KR.md#볼트가-끝날-때) 참고). 그때 터미널은 `state=zeroized`를 보여 주며, 새 키에는 재부팅이 필요합니다. +- **시간이 걸린 루프는 머신에서 테스트하지 않음**: 커밋된 테스트 가운데 서비스 중에 실제 터미널이나 실제 볼트를 끝내는 것은 없습니다. 대기, 3번이라는 한도, 터미널이 내려갔을 때 볼트를 멈추는 것, `root: supervision over`는 모형 호스트를 쓰는 `k0-sup`의 호스트 테스트만 다룹니다. 부팅 자가 테스트는 실제 커널에서 걷어 내기, 지우기, 다시 만들기를 서비스마다 재시작 한 번으로, 대기 없이 다룹니다. `root: vault erased before exit`와 `root: vault not erased`에도 테스트가 없습니다. +- **감독이 끝난 뒤**: 루트 태스크가 타임아웃 없이 기다리고 콘솔 입력을 기다리는 태스크도 없으면, 커널의 idle 규칙이 `k0: all tasks stopped (none ready, no timeout pending)`를 한 번 출력합니다([scheduling_KR.md](scheduling_KR.md#실행할-태스크가-없을-때) 참고). 커밋된 테스트 가운데 이것을 실행하는 것은 없습니다. - **부트 로그 몫**: 터미널 출력은 메모리 부트 로그의 사용자 몫을 소모합니다. 그 몫이 가득 차면 이후 태스크 출력은 거기에 기록되지 않습니다. - **볼트의 이전 한계는 모두 유지**: 구현은 검증되지 않았고, 부채널 분석이 없고, 키는 승인된 난수 비트 생성기에서 나오지 않고, 영속성이 없고, 양자 내성 알고리즘이 없습니다. 가용성은 보호되지 않습니다([ipc_KR.md](ipc_KR.md) 참고). diff --git a/design/kr/uefi_KR.md b/design/kr/uefi_KR.md index e527ad8..e53539b 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 호스트에서 415개(`k0-abi` 15, `k0-cap` 54, `k0-boot` 85, `k0-efi` 33, `k0-conin` 19, `k0-slice` 9, `k0-part` 36, Ed25519 포함 20개와 제외 11개의 `k0-vault`, 볼트 feature 포함 24개와 제외 21개의 `k0-term`, 두 그래뉼 각각에 `k0-mm` 44)를, `k0-mm` 테스트를 건너뛰는 그 밖의 호스트에서 327개를 실행합니다. +- **호스트 테스트 스크립트**: `tools/host-test.sh`는 이제 ARM 호스트에서 457개(`k0-abi` 16, `k0-cap` 71, `k0-boot` 85, `k0-efi` 33, `k0-conin` 19, `k0-slice` 9, `k0-part` 36, `k0-sup` 20, Ed25519 포함 22개와 제외 13개의 `k0-vault`, 볼트 feature 포함 24개와 제외 21개의 `k0-term`, 두 그래뉼 각각에 `k0-mm` 44)를, `k0-mm` 테스트를 건너뛰는 그 밖의 호스트에서 369개를 실행합니다. - **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 315c831..392a124 100644 --- a/design/kr/vault_KR.md +++ b/design/kr/vault_KR.md @@ -6,7 +6,7 @@ -이 노트는 K0의 격리 코어 위에 올라가는 첫 번째 서비스를 설명합니다. **볼트** 태스크가 Ed25519 키 하나를 보관합니다. 클라이언트 태스크는 IPC로 서명과 공개 키를 받고, 키는 받지 못합니다. 코드는 `userspace/k0-vault`(크레이트), `userspace/root-task/src/oracle.rs`(연결과 자가 테스트), `userspace/root-task/src/service.rs`(자가 테스트 뒤에 시작하는 서비스), `crates/k0-boot`(부팅 시드)에 있습니다. `terminal`로 빌드한 이미지에서는 직렬 터미널이 볼트의 운영자입니다("서비스 볼트와 운영자" 절 참고). +이 노트는 K0의 격리 코어 위에 올라가는 첫 번째 서비스를 설명합니다. **볼트** 태스크가 Ed25519 키 하나를 보관합니다. 클라이언트 태스크는 IPC로 서명과 공개 키를 받고, 키는 받지 못합니다. 코드는 `userspace/k0-vault`(크레이트), `userspace/root-task/src/oracle.rs`(연결과 자가 테스트), `userspace/root-task/src/service.rs`(자가 테스트 뒤에 시작하는 서비스와 그 감독), `crates/k0-boot`(부팅 시드)에 있습니다. `terminal`로 빌드한 이미지에서는 직렬 터미널이 볼트의 운영자입니다("서비스 볼트와 운영자" 절 참고). > [!NOTE] > 볼트는 선택 사항이며 기본값은 꺼짐입니다. 기본 이미지에는 볼트도 암호 코드도 없습니다. @@ -75,7 +75,7 @@ | `fresh` | 시드도 키도 없음 | | `seeded` | `INIT`이 엔트로피 규칙을 통과한 시드를 넘겼고 볼트가 쥐고 있음 | | `ready` | `KEYGEN`이 키를 만들고 시드를 지움 | -| `zeroized` | `ZEROIZE`가 키와 시드를 지움. 새 키는 재부팅해야 만들 수 있음 | +| `zeroized` | `ZEROIZE`가 키와 시드를 지웠거나, 볼트가 끝난 뒤 다시 시작됨([볼트가 끝날 때](#볼트가-끝날-때) 참고). 새 키는 재부팅해야 만들 수 있음 | | `failed` | 자가 테스트 또는 쌍 일관성 테스트가 실패함. 이 상태로 가는 모든 길에서 시드와 키를 지움 | 키는 부팅당 하나입니다. 두 번째 `KEYGEN`은 `KEY_EXISTS`(터미널에서는 `key-exists`)로 거부됩니다. @@ -119,15 +119,39 @@ operator는 서명을 받을 수도 시드를 넘길 수도 없습니다. 배지 ## 서비스 볼트와 운영자 -진짜 부트 시드는 정확히 한 번 쓰입니다. `terminal`과 `vault`로 빌드한 이미지에서 루트 태스크는 먼저 자가 테스트를 모두 실행합니다. 그다음 새 볼트인 **서비스 볼트**를 띄우고 `INIT`으로 부트 시드를 넘깁니다. 그리고 `root: vault seeded`, `root: vault has no seed (boot seed has no entropy)`, `root: vault has no seed (no algorithm in this image)` 중 하나를 출력합니다. 그 밖의 모든 이미지에서 루트 태스크는 진입하자마자 시드를 지웁니다. +진짜 부트 시드는 정확히 한 번 쓰입니다. `terminal`과 `vault`로 빌드한 이미지에서 루트 태스크는 먼저 자가 테스트를 모두 실행합니다. 그다음 시드를 받지 않는 볼트로 재시작 경로를 시험합니다(`root: vault restart test pass`, [terminal_KR.md](terminal_KR.md#부팅-때의-재시작-경로) 참고). 그 뒤 새 볼트인 **서비스 볼트**를 띄우고 `INIT`으로 부트 시드를 넘깁니다. 그리고 `root: vault seeded`, `root: vault has no seed (boot seed has no entropy)`, `root: vault has no seed (no algorithm in this image)` 중 하나를 출력합니다. 넘긴 뒤에 루트 태스크는 자기 쪽 시드 사본과 사용한 요청 프레임을 지웁니다. 그 밖의 모든 이미지에서 루트 태스크는 진입하자마자 시드를 지웁니다. -이어서 루트 태스크는 터미널과 똑같이 배선한 적대적 태스크 둘을 실행합니다. 둘은 거부되어야 하고 폴트로 끝나야 합니다. 그 뒤 루트 태스크는 자신의 admin 케이퍼빌리티를 버리고, 터미널을 시작하고, 영원히 대기합니다. 터미널은 operator 배지로 서비스 볼트에 `STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`만 요청할 수 있습니다. 터미널의 명령, 화면, 한계는 [USAGE_KR.md](../../USAGE_KR.md)에 있습니다. +이어서 루트 태스크는 터미널과 똑같이 배선한 적대적 태스크 둘을 실행합니다. 둘은 거부되어야 하고 폴트로 끝나야 합니다. 그 뒤 루트 태스크는 서비스 볼트가 여전히 같은 상태인지 확인하고, 자신의 admin 케이퍼빌리티를 버리고, 터미널을 시작합니다. 그때부터 두 서비스를 감독합니다([terminal_KR.md](terminal_KR.md#감독) 참고). 터미널은 operator 배지로 서비스 볼트에 `STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`만 요청할 수 있습니다. 터미널의 명령, 화면, 한계는 [USAGE_KR.md](../../USAGE_KR.md)에 있습니다. > [!WARNING] > 직렬 선에는 인증이 없습니다. 선에 닿는 사람은 누구나 operator이며, 키 소거를 포함한 operator의 네 연산을 그대로 할 수 있습니다. operator는 서명을 받을 수 없고 정책을 바꿀 수 없습니다. 자가 테스트 볼트는 다른 볼트입니다. 공개된 RFC 8032 시험 시드와 진짜 시드 정보로 키를 만들어서 엔트로피 규칙은 그대로 실행되고, 진짜 시드는 이 볼트에 닿지 않습니다. +### 볼트가 끝날 때 + +루트 태스크는 두 번째 틱마다 서비스 볼트가 아직 살아 있는지 커널에 묻습니다([terminal_KR.md](terminal_KR.md#감독) 참고). 볼트 태스크가 끝났으면, 이유가 무엇이든 루트 태스크는 그 메모리로 다른 일을 하기 전에 볼트의 메모리를 지웁니다. + +1. 볼트의 슬랩을 회수합니다. 슬랩은 루트 태스크의 CNode에 있는 16 그래뉼짜리 자식 untyped이고, 볼트의 주소 공간, 스택, CNode, TCB가 모두 거기서 나왔습니다. 회수하면 그 전부가 제거됩니다. +2. 슬랩의 16 그래뉼 전부를 프레임으로 retype하고 전부 쥐고 있습니다. `CAP_REVOKE`는 메모리를 0으로 채우지 않고, `RETYPE`은 내주는 그래뉼마다 0으로 채웁니다. 17번째 `RETYPE`은 `EXHAUSTED`를 반환해야 하며, 이것으로 프레임 16개가 슬랩 전체를 덮었음을 확인합니다. +3. 슬랩을 다시 회수합니다. 프레임이 사라지고 슬랩은 비게 됩니다. +4. operator 응답 프레임을 0으로 채웁니다. 이 프레임은 슬랩 밖에 있고 마지막 공개 키가 남아 있을 수 있습니다. + +터미널이 완전히 내려가서 루트 태스크가 아직 올라와 있는 볼트를 멈출 때에도 같은 단계를 실행합니다. 1단계부터 3단계까지는, 서비스 볼트가 시드를 받은 뒤 루트 태스크가 실패한 점검으로 종료하기 직전에도 시도로서 실행됩니다. 그때 루트 태스크는 `root: vault erased before exit` 또는 `root: vault not erased`를 출력합니다. + +3번이라는 재시작 한도가 남아 있으면 루트 태스크는 대기 뒤에 같은 슬랩과 같은 슬롯에 볼트를 다시 만듭니다. 그 볼트는 `userspace/k0-vault/src/server.rs`의 `Vault::retired`로 만듭니다. + +- **상태**: 다른 볼트와 마찬가지로 자가 테스트를 실행한 뒤 `fresh`가 아니라 `zeroized` 상태로 시작합니다. 자가 테스트가 실패하면 `failed`입니다. +- **시드 없음**: admin이 보낸 것을 포함해 `INIT`을 `DENIED`로 거부합니다. `fresh` 상태였다면 아직 시드를 받을 수 있는 볼트처럼 보였을 것입니다. +- **키 없음**: `KEYGEN`, `SIGN`, `PUBLIC_KEY`는 지워진 볼트의 답을 받습니다(`ZEROIZED`, 알고리즘이 없는 이미지에서는 `UNSUPPORTED`). `STATUS`와 `ZEROIZE`는 그대로 동작합니다. + +루트 태스크에는 두 번째로 줄 시드가 없습니다. 부트 시드를 첫 서비스 볼트에 한 번 넘겼고, 자기 쪽 사본을 지웠으며, 서비스를 시작하기 전에 admin 케이퍼빌리티를 버렸습니다. + +> [!IMPORTANT] +> 볼트를 다시 시작한 뒤에는 머신을 다시 부팅할 때까지 키가 없습니다. 로그 줄은 `root: vault started again without a key`이고, 터미널에서 `vault status`는 `state=zeroized`를 보여 줍니다. + +`vault-ed25519`에서는 그때 `vault keygen ed25519`와 `vault pubkey`가 `err zeroized`로 답합니다. 볼트 하나가 끝난 뒤 다음 볼트가 시작되기 전까지처럼 실행 중인 볼트가 없는 동안에는 터미널의 볼트 명령이 수신자를 찾지 못합니다. 터미널의 타임아웃인 5틱 안에 호출을 받는 볼트가 없으면 명령은 `err vault-timeout`으로 답합니다. + ## feature와 고정된 이미지 `k0-kernel` 크레이트에는 feature가 둘 있으며 feature는 더하기만 합니다. @@ -151,12 +175,12 @@ $ cargo build -p k0-kernel --features console,vault-ed25519 ## 테스트 방법 -**호스트 테스트**(`tools/host-test.sh`가 알고리즘 feature 유무로 `k0-vault`를 실행합니다). 테스트는 `userspace/k0-vault/src/tests.rs`에 있으며 Ed25519가 있으면 20개, 없으면 11개입니다. 이름은 다음과 같습니다. +**호스트 테스트**(`tools/host-test.sh`가 알고리즘 feature 유무로 `k0-vault`를 실행합니다). 테스트는 `userspace/k0-vault/src/tests.rs`에 있으며 Ed25519가 있으면 22개, 없으면 13개입니다. 이름은 다음과 같습니다. -- 항상: `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`(마지막 것은 알고리즘이 없을 때만). +- 항상: `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`, `a_vault_started_again_takes_no_seed_and_makes_no_key`, `a_fresh_vault_and_one_started_again_differ_only_in_the_state`, 그리고 `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 호스트에서 415개, 그 외 호스트에서 327개입니다(`k0-mm` 제외). +다른 크레이트와 합치면 호스트 테스트는 ARM 호스트에서 457개, 그 외 호스트에서 369개입니다(`k0-mm` 제외). 볼트를 언제 걷어 내고 다시 시작할지 정하는 정책은 `userspace/k0-sup`에 있고 자체 호스트 테스트 20개가 있습니다([terminal_KR.md](terminal_KR.md#테스트-방법) 참고). **루트 태스크 자가 테스트**(`userspace/root-task/src/oracle.rs`의 `test_oracle`, `vault`로 빌드한 이미지에만 있음). 다음을 검사합니다. @@ -173,6 +197,8 @@ $ cargo build -p k0-kernel --features console,vault-ed25519 표지는 `root: oracle tests pass`입니다. 클라이언트 태스크는 루트 CNode 슬롯이 부족해 하나의 클라이언트 주소 공간에서 차례로 실행됩니다. 이 테스트는 볼트와 클라이언트 사이의 격리를 보여 주며 클라이언트끼리의 격리는 보여 주지 않습니다. +**부팅 때의 재시작 테스트**(`terminal`과 `vault`로 빌드한 이미지에만 있음, 표지 `root: vault restart test pass`). 서비스 볼트가 생기기 전에 루트 태스크가 같은 자리에 볼트를 만들고, 끝내고, 감독자의 폴 한 번으로 걷어 내고 지우고 다시 만들게 합니다. 그런 다음 새 볼트가 `zeroized`를 보고하고 `INIT`을 거부하는지 확인합니다. 단계는 [terminal_KR.md](terminal_KR.md#부팅-때의-재시작-경로)에 있습니다. 이 테스트는 지운 메모리를 다시 읽어 보지 않습니다. 회수하고 retype한 슬랩이 0으로 읽히는지는 다른 슬랩에서, 모든 이미지의 분할 자가 테스트가 24 그래뉼 가운데 넷을 읽어 확인합니다(`root: untyped split tests pass`, [capabilities_KR.md](capabilities_KR.md#테스트-방법) 참고). + **부팅 매트릭스 행**: `vault`, `vault-max`(RNDR), `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`, 그리고 정적 행 `vault-symbols`(기본 이미지에는 볼트나 암호 코드가 없고, 볼트 이미지에는 그 코드에서 온 쓰기 가능한 정적 변수가 없음)입니다. 매트릭스는 HVF가 있는 Mac에서 82행, CI에서 71행입니다. 터미널용 행은 `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi`, `hvf-term`입니다. `tools/term-test.py `는 QEMU의 직렬 포트를 파이프에 연결해 터미널 이미지를 부팅하고 스크립트로 짠 세션을 실행합니다. 이제 모든 이미지는 `k0: dtb seeds wiped B`와 `root: boot seed from rng-seed bytes ...`도 출력합니다. ## 알려진 공백 @@ -182,7 +208,10 @@ $ cargo build -p k0-kernel --features console,vault-ed25519 - **키 하나**: 영속성, 키 가져오기·내보내기, DRBG, 양자 내성 알고리즘이 아직 없습니다. 새 키를 만들려면 재부팅해야 합니다. - **서비스 모드에 서명 클라이언트 없음**: 서비스 볼트의 키는 만들어지고 표시되지만 아직 다른 태스크가 쓰지 않습니다. 클라이언트 서명은 자가 테스트가 보여 줍니다. -- **터미널과 볼트는 죽어도 다시 시작하지 않습니다**: 죽으면 그대로 멈춥니다. 루트 태스크는 신뢰 대상입니다. +- **다시 시작한 볼트에는 키가 없습니다**: 감독자는 끝난 볼트를 부팅당 최대 세 번 다시 시작하지만, 새 볼트에는 시드도 키도 없고 어느 것도 받지 않습니다. 끝난 볼트의 키는 사라졌고, 새 키를 만들려면 재부팅해야 합니다. +- **서비스 중의 소거는 다시 읽어 확인하지 않습니다**: 루트 태스크는 끝난 볼트의 슬랩을 전부 retype해서 지우고, 프레임 16개가 슬랩을 덮는지 확인합니다. 프레임을 매핑해서 읽어 보지는 않습니다. 슬랩 밖에 있는 것은 이 소거가 다루지 않습니다. operator 응답 프레임은 루트 태스크가 따로 0으로 채우고, 펌웨어나 UEFI 로더가 가진 시드 사본은 지워지지 않습니다(부팅 시드 경로 절의 참고를 보십시오). +- **실제 볼트를 끝내는 테스트가 없습니다**: 커밋된 테스트 가운데 서비스 중에 서비스 볼트를 끝내는 것은 없습니다. 재시작 경로는 부팅할 때마다 시드가 없는 볼트로 한 번, 대기 없이 실행되고, 시간이 걸린 정책은 호스트에서 모형으로 테스트합니다([terminal_KR.md](terminal_KR.md#알려진-공백) 참고). +- **멈춰 있는 볼트는 알아채지 못합니다**: 감독자는 끝난 태스크만 보며, 그것도 최대 두 틱 늦게 봅니다. - **가용성은 보호되지 않습니다**: 클라이언트는 엔드포인트 하나를 공유하며 모든 호출에 타임아웃을 써야 합니다([ipc_KR.md](ipc_KR.md) 참고). CPU를 계속 쓰는 태스크 하나 뒤에서는 호출자와 볼트가 왕복 한 번에 스케줄러 모델에서 4틱을 쓰며, 이전에는 2틱이었습니다. 터미널의 호출은 5틱 타임아웃을 쓰고, 고정 이미지의 서비스 모드에는 CPU를 계속 쓰는 태스크가 없습니다. - **루트 태스크는 신뢰 대상입니다**: 볼트를 만들고 읽을 수 있습니다. - **자기만의 도메인이 없습니다**: 볼트는 아직 자기만의 시간 분할 도메인에 있지 않습니다. 루트 태스크가 자가 테스트의 끝에서 시간 분할의 제어 케이퍼빌리티를 삭제하므로, 볼트와 그 클라이언트와 터미널은 모두 루트 도메인에서 실행됩니다. 이들이 스케줄러를 통해 서로에 대해 알게 되는 것에는 제한이 없습니다([scheduling_KR.md](scheduling_KR.md#시간-분할) 참고). diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index 7b301fc..3dcd375 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -101,6 +101,8 @@ extern "C" fn k0_syscall(ctx: &mut Context) { nr::CAP_REVOKE => Some(sys_cap_revoke(a[0])), nr::PART_SET_TABLE => Some(sys_part_set_table(a[0], a[1], [a[2], a[3], a[4], a[5]])), nr::PART_SET_DOMAIN => Some(sys_part_set_domain(a[0], a[1], a[2])), + nr::UNTYPED_SPLIT => Some(sys_untyped_split(a[0], a[1], a[2])), + nr::TCB_STATUS => Some(sys_tcb_status(a[0])), // IPC는 블록 경로에서 반환 레지스터를 미래의 상대가 기록하므로 // 핸들러가 ctx 기록까지 직접 책임짐. false는 호출한 태스크가 // 블록됐는데 준비된 태스크가 없다는 뜻이고, 그때는 커널이 기다림 @@ -428,6 +430,7 @@ fn cap_err(e: CapError) -> i64 { CapError::NoRights => err::NO_RIGHTS, CapError::BadBadge => err::BAD_BADGE, CapError::TooDeep => err::TOO_DEEP, + CapError::BadSize => err::BAD_SIZE, CapError::PrepFailed | CapError::OutOfSlots | CapError::BadRegion => err::KERNEL_RESOURCE, CapError::Corrupt => k0_arch::fatal("cap derivation list corrupt"), } @@ -520,6 +523,31 @@ fn sys_retype(ut: u64, kind: u64, dest: u64) -> i64 { })()) } +/// UNTYPED_SPLIT 시스템 콜 처리 함수입니다. +/// +/// untyped에서 더 작은 자식 untyped를 잘라냅니다. 장부만 바꾸는 연산이라 +/// 별칭 매핑도 소거도 등록부도 건드리지 않고, 커널 자원을 쓰지 않으므로 +/// KERNEL_RESOURCE로 실패하지 않습니다. 잘라낸 메모리는 RETYPE가 오브젝트로 +/// 만들 때 지워집니다. 그래뉼 수 검사는 RETYPE의 타입 검사처럼 슬롯 조회보다 +/// 먼저입니다. +/// +/// # Arguments +/// `ut` - untyped 슬롯(x0) +/// `granules` - 자식의 그래뉼 수(x1) +/// `dest` - 자식 untyped를 받을 빈 슬롯(x2) +fn sys_untyped_split(ut: u64, granules: u64, dest: u64) -> i64 { + if granules == 0 { + return err::BAD_SIZE; + } + done((|| { + let cn = cspace()?; + let ut = cn.slot(ut).ok_or(err::BAD_SLOT)?; + let dest = cn.slot(dest).ok_or(err::BAD_SLOT)?; + // SAFETY: 두 슬롯은 살아 있는 CNode의 범위 안 슬롯이고 접근이 배타적임 + unsafe { k0_cap::split(ut, dest, granules, k0_mm::GRANULE as u64) }.map_err(cap_err) + })()) +} + /// 슬롯에서 AddrSpace 케이퍼빌리티를 읽고 등록부로 살아 있음을 확인하는 /// 함수입니다. (루트 PA, asid, 세대)를 줍니다. /// @@ -962,3 +990,51 @@ fn sys_tcb_resume(slot: u64) -> i64 { Ok(()) })()) } + +/// TCB_STATUS 시스템 콜 처리 함수입니다. +/// +/// TCB 케이퍼빌리티가 가리키는 태스크가 시작 전인지, 살아 있는지, 끝났는지를 +/// 돌려줍니다. 아무것도 쓰지 않으므로 실패한 호출도 성공한 호출도 슬롯, TCB, +/// 큐, 스케줄러를 그대로 둡니다. 끝난 까닭은 돌려주지 않습니다. 종료 코드와 +/// 끝나는 방식은 끝나는 태스크가 고르는 값이라 그것으로 판단하게 두지 +/// 않습니다. 대기 상태들도 구별해 주지 않습니다. +/// +/// Dead는 최종 상태입니다(teardown은 Dead에서 바로 돌아오고, 구성은 +/// Inactive, 재개는 Stopped만 받음). 그래서 주기적으로 묻는 쪽이 끝난 것을 +/// 놓치는 일이 없습니다. +/// +/// # Arguments +/// `slot` - TCB 슬롯(x0) +fn sys_tcb_status(slot: u64) -> i64 { + use k0_abi::tcb_status as st; + + let state = (|| { + let cn = cspace()?; + let (_, e) = lookup(&cn, slot)?; + let Cap::Tcb { base } = e.cap else { + return Err(err::BAD_CAP); + }; + let t = kva(base) as *const Tcb; + // SAFETY: t는 살아 있는 TCB 케이퍼빌리티가 가리키는 전용 프레임의 + // 별칭이고 그 프레임은 케이퍼빌리티가 있는 동안 다른 것으로 + // 쓰이지 않음. 상태 필드 하나만 읽고 참조를 만들지 않으므로, + // 호출한 태스크가 자기 자신을 물어도 저장된 컨텍스트와 겹치는 + // 참조가 생기지 않음 + Ok(unsafe { (*t).state }) + })(); + // 상태를 하나씩 적음. 상태가 늘면 여기서 컴파일이 멈추므로 어느 값으로 + // 보일지 정하지 않은 채 넘어가는 일이 없음 + match state { + Err(e) => e, + Ok(TaskState::Inactive | TaskState::Stopped) => st::NOT_STARTED, + Ok(TaskState::Ready + | TaskState::Running + | TaskState::BlockedSend + | TaskState::BlockedRecv + | TaskState::BlockedReply + | TaskState::BlockedCall) => st::ALIVE, + #[cfg(feature = "console-input")] + Ok(TaskState::BlockedConsole) => st::ALIVE, + Ok(TaskState::Dead) => st::ENDED, + } +} diff --git a/tools/host-test.sh b/tools/host-test.sh index c0d2345..2941ed1 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 -p k0-slice -p k0-part "$@" +cargo test --offline --target "$host" -p k0-abi -p k0-cap -p k0-boot -p k0-efi -p k0-conin -p k0-slice -p k0-part -p k0-sup "$@" # 키 볼트: 알고리즘을 넣은 것과 뺀 것을 따로 돌림(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 d132647..f6579b3 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: slice test yield pass|root: slice test block pass|root: preempt test pass|root: partition refusal pass|root: partition window 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: partition sealed|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: tcb status tests pass|root: slice test yield pass|root: slice test block pass|root: preempt test pass|root: partition refusal pass|root: partition window 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: untyped split tests pass|root: revocation tests pass|root: kernel reserve tests pass|root: partition sealed|root: sched tests pass|k0: tick " # 메모리의 로그에는 처음 몇 번의 틱만 남습니다. 자가 검증이 그보다 오래 걸리는 # 호스트에서는 끝의 틱이 로그에 없을 수 있으므로 순서 목록에서는 빼고, 첫 틱이 # 기록됐는지와(아래) 자가 검증 뒤에도 틱이 이어지는지를(위의 대기) 따로 봅니다. @@ -198,11 +198,12 @@ off) exit 2 ;; esac -# 터미널이 든 이미지: 자가 검증 뒤에 서비스가 시작되는 줄들. 터미널과 똑같이 -# 배선한 적대적 태스크 둘이 폴트로 끝나야 함 +# 터미널이 든 이미지: 자가 검증 뒤에 서비스가 시작되는 줄들. 볼트를 다시 띄우는 +# 경로의 검증이 먼저이고, 터미널과 똑같이 배선한 적대적 태스크 둘이 터미널의 +# 자리에서 차례로 폴트로 끝나야 함(그때마다 자리를 회수하고 다시 만듦) case "$service_rule" in -vault) markers="$markers|root: vault |root: terminal console filter [?|root: terminal wiring holds|k0: task fault dabort-lower|k0: task fault dabort-lower|root: service started" ;; -plain) markers="$markers|root: terminal console filter [?|root: terminal wiring holds|k0: task fault dabort-lower|k0: task fault dabort-lower|root: service started" ;; +vault) markers="$markers|root: vault restart test pass|root: vault |root: terminal console filter [?|root: terminal wiring holds|k0: task fault dabort-lower|k0: task fault dabort-lower|root: terminal restart test pass|root: service started" ;; +plain) markers="$markers|root: terminal console filter [?|root: terminal wiring holds|k0: task fault dabort-lower|k0: task fault dabort-lower|root: terminal restart test pass|root: service started" ;; none) markers="$markers|root: no console input, terminal not started" ;; "") ;; *) diff --git a/tools/term-test.py b/tools/term-test.py index f1c6d7b..d7acb01 100755 --- a/tools/term-test.py +++ b/tools/term-test.py @@ -41,7 +41,10 @@ b"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", b"3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29", ) -FAIL_RE = re.compile(rb"root: FAIL|k0: EXCEPTION|k0: PANIC|k0: FATAL|k0: UNEXPECTED|k0: task fault|k0: all tasks|k0: tick ") +# 프롬프트가 뜬 뒤에는 루트 태스크의 줄이 하나도 없어야 함. 감독자는 서비스가 +# 끝났을 때만 줄을 내므로, 멀쩡한 세션에서 `root: ` 줄이 보이면 일어나지 않아야 +# 할 재시작이 일어난 것임 +FAIL_RE = re.compile(rb"root: |k0: EXCEPTION|k0: PANIC|k0: FATAL|k0: UNEXPECTED|k0: task fault|k0: all tasks|k0: tick ") class Failure(Exception): diff --git a/userspace/k0-sup/Cargo.toml b/userspace/k0-sup/Cargo.toml new file mode 100644 index 0000000..42012b9 --- /dev/null +++ b/userspace/k0-sup/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "k0-sup" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +# 의존하는 크레이트가 없습니다. 시스템 콜도 쓰지 않으므로 호스트에서 그대로 +# 시험합니다. +[dependencies] diff --git a/userspace/k0-sup/src/lib.rs b/userspace/k0-sup/src/lib.rs new file mode 100644 index 0000000..245d039 --- /dev/null +++ b/userspace/k0-sup/src/lib.rs @@ -0,0 +1,367 @@ +//! 서비스(운영자 터미널과 키 볼트)를 감독하는 정책 크레이트입니다. +//! +//! # Features +//! 루트 태스크는 서비스를 시작한 뒤 일정한 주기로 [Supervisor::poll]을 +//! 부릅니다. 이 함수가 서비스의 태스크가 끝났는지 묻고, 끝난 것을 회수하고, +//! 한도 안에서 다시 띄우고, 알릴 줄을 정합니다. 시스템 콜은 쓰지 않고 바깥과는 +//! [Host] 트레이트로만 이어지므로, 부팅 자가 시험과 서비스의 폴 루프가 같은 +//! 함수를 쓰고 정책 전체를 호스트에서 시험합니다. 할당도 가변 static도 +//! `unsafe`도 없습니다. +//! +//! 정책은 다음과 같습니다. +//! +//! - 끝난 서비스는 그 폴에서 곧바로 회수합니다. 다시 띄우지 않을 때도 +//! 회수합니다(볼트의 회수에는 메모리 소거가 들어 있음). +//! - 서비스마다 부팅당 다시 띄우는 횟수에 상한이 있고 채워지지 않습니다. +//! k번째로 다시 띄우기 전에는 [Limits::backoff]의 k번째 값만큼 폴을 +//! 기다립니다. 상한을 다 쓴 서비스는 재부팅까지 내려가 있습니다. +//! - 태스크가 왜 끝났는지는 쓰지 않습니다. 종료 코드와 끝나는 방식은 끝나는 +//! 태스크가 고르는 값입니다. +//! - 터미널은 콘솔 입력 경로가 없으면 다시 띄우지 않고 한도도 쓰지 않습니다. +//! 입력 경로는 터미널이 끝난 것을 본 뒤와 다시 만들기 직전에만 묻습니다. +//! 살아 있는 터미널의 입력을 건드리지 않으려는 것입니다. +//! - 볼트를 부를 수 있는 태스크는 터미널뿐입니다. 터미널이 완전히 내려가면 +//! 살아 있는 볼트도 그 폴에서 내리고 지웁니다. 쓸 태스크가 없는 키를 +//! 메모리에 남기지 않습니다. +//! - 모든 서비스가 내려가면 한 줄을 남기고 감독이 끝납니다. +//! +//! 감독자가 서비스에 기대지 않게 하려고, 이 크레이트는 서비스에게 무엇도 +//! 묻지 않습니다. 묻는 상대는 언제나 커널입니다([Host::ended], +//! [Host::input_present]). +//! +//! # Errors +//! 이 크레이트의 함수는 실패하지 않습니다. 회수나 다시 만들기가 실패했을 때 +//! 무엇을 할지는 [Host]를 구현하는 쪽의 몫입니다(루트 태스크는 볼트의 +//! 메모리를 지우기를 시도한 뒤 끝남). + +#![cfg_attr(not(test), no_std)] +#![forbid(unsafe_code)] + +#[cfg(test)] +mod tests; + +/// 감독하는 서비스를 나타내는 열거형입니다. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Id { + /// 운영자 터미널 + Terminal, + /// 키 볼트 + Vault, +} + +/// 감독의 한도를 담는 구조체입니다. +/// +/// 한도는 상수가 아니라 값입니다. 부팅 자가 시험은 기다림이 없는 한도로 같은 +/// 함수를 돌립니다. +#[derive(Clone, Copy, Debug)] +pub struct Limits { + /// k번째로 다시 띄우기 전에 기다리는 폴 수입니다. 길이가 곧 서비스마다 + /// 부팅당 다시 띄우는 횟수의 상한입니다. 0이면 끝난 것을 본 폴에서 바로 + /// 다시 만들고, n이면 그 폴에서 n번째 뒤의 폴에서 다시 만듭니다 + pub backoff: &'static [u32], + /// 폴 한 주기의 틱 수. 알리는 줄에 적는 수에만 씁니다 + pub period: u32, +} + +/// 서비스 모드에서 쓰는 한도입니다. 부팅당 3번, 끝난 것을 본 폴부터 적어도 +/// 1, 4, 16폴(2, 8, 32틱) 뒤에 다시 띄웁니다. +pub const LIMITS: Limits = Limits { + backoff: &[1, 4, 16], + period: 2, +}; + +/// 서비스가 다시 뜨지 않는 이유를 나타내는 열거형입니다. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Why { + /// 콘솔 입력 경로가 없음(터미널) + NoInput, + /// 다시 띄우는 횟수의 상한을 다 씀 + Spent, + /// 터미널이 완전히 내려가 부를 태스크가 없음(볼트) + NoTerminal, +} + +/// 서비스 하나의 상태를 나타내는 열거형입니다. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum State { + /// 이 이미지에 없는 서비스 + Absent, + /// 시작돼 있음. 폴마다 끝났는지 물음 + Up, + /// 회수했고, 이만큼의 폴 뒤에 다시 만듦(1이면 다음 폴) + Wait(u32), + /// 내려갔고 이 부팅에서는 다시 띄우지 않음 + Down(Why), +} + +/// 감독자가 알리는 줄을 나타내는 열거형입니다. +/// +/// 문구는 [Line::write]가 만듭니다. 부팅 시험 스크립트가 실패로 읽는 낱말은 +/// 어느 줄에도 들어 있지 않습니다(호스트 시험이 확인함). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Line { + /// 끝난 서비스를 회수했고 다시 띄울 것임 + Restart { + id: Id, + /// 몇 번째로 다시 띄우는지(1부터) + restart: u32, + /// 상한 + of: u32, + /// 그 전에 기다리는 최소 틱 수 + ticks: u32, + }, + /// 서비스를 다시 띄웠음 + Started(Id), + /// 끝난 서비스를 회수했고 다시 띄우지 않음 + NotAgain(Id, Why), + /// 살아 있던 볼트를 내리고 지웠음(터미널이 완전히 내려감) + Stopped, + /// 모든 서비스가 내려가 감독이 끝남 + Over, +} + +impl Line { + /// 줄의 문구를 조각으로 내보내는 함수입니다. 줄 끝 문자까지 냅니다. + /// + /// # Arguments + /// `out` - 조각을 차례로 받는 함수 + pub fn write(&self, mut out: impl FnMut(&str)) { + let name = |id: Id| match id { + Id::Terminal => "root: terminal ended", + Id::Vault => "root: vault ended and erased", + }; + match *self { + Line::Restart { id, restart, of, ticks } => { + out(name(id)); + out(", restart "); + number(restart, &mut out); + out(" of "); + number(of, &mut out); + out(" after at least "); + number(ticks, &mut out); + out(" ticks"); + } + Line::Started(Id::Terminal) => out("root: terminal started again"), + Line::Started(Id::Vault) => out("root: vault started again without a key"), + Line::NotAgain(id, why) => { + out(name(id)); + out(match why { + Why::NoInput => ", no console input, not started again", + Why::Spent => ", restart budget spent, not started again", + Why::NoTerminal => ", no terminal, not started again", + }); + } + Line::Stopped => out("root: vault stopped and erased, no terminal"), + Line::Over => out("root: supervision over"), + } + out("\n"); + } +} + +/// 수를 십진수로 내보내는 함수입니다. +fn number(mut v: u32, out: &mut impl FnMut(&str)) { + const DIGITS: [&str; 10] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; + let mut place = 1u32; + while v / place >= 10 { + place *= 10; + } + loop { + out(DIGITS[(v / place) as usize]); + v %= place; + if place == 1 { + break; + } + place /= 10; + } +} + +/// 감독자가 바깥에 시키는 일을 나타내는 트레이트입니다. +/// +/// 루트 태스크는 시스템 콜로 구현하고 호스트 시험은 기록하는 모형으로 +/// 구현합니다. 어느 함수도 서비스의 응답을 기다리지 않아야 합니다. +pub trait Host { + /// 서비스의 태스크가 끝났는지 묻는 함수입니다. + /// + /// 시작돼 있는 서비스마다 폴 한 번에 한 번 불립니다. + fn ended(&mut self, id: Id) -> bool; + + /// 콘솔 입력 경로가 있는지 묻는 함수입니다. + /// + /// 터미널이 끝난 것을 보고 회수한 뒤와, 터미널을 다시 만들기 직전에만 + /// 불립니다. 터미널이 시작돼 있는 동안에는 불리지 않습니다. + fn input_present(&mut self) -> bool; + + /// 서비스의 것을 전부 회수하는 함수입니다. 볼트는 메모리 소거까지 합니다. + /// + /// 끝난 서비스에도, 살아 있는 볼트를 내릴 때도 불립니다. + fn retire(&mut self, id: Id); + + /// 회수한 자리에 서비스를 다시 만들어 시작하는 함수입니다. + fn rebuild(&mut self, id: Id); + + /// 줄 하나를 알리는 함수입니다. + fn line(&mut self, line: Line); +} + +/// 서비스 하나의 장부입니다. +#[derive(Clone, Copy, Debug)] +struct Slot { + state: State, + /// 지금까지 다시 띄우기로 한 횟수 + used: u32, +} + +/// 터미널과 볼트를 감독하는 상태 기계를 담는 구조체입니다. +#[derive(Clone, Copy, Debug)] +pub struct Supervisor { + limits: Limits, + term: Slot, + vault: Slot, + /// 감독이 끝났다는 줄을 이미 냈음 + over: bool, +} + +impl Supervisor { + /// 서비스가 막 시작된 상태의 감독자를 만드는 함수입니다. + /// + /// # Arguments + /// `limits` - 다시 띄우는 한도 + /// `vault` - 이 이미지에 볼트가 있는지 + pub const fn new(limits: Limits, vault: bool) -> Self { + Supervisor { + limits, + term: Slot { state: State::Up, used: 0 }, + vault: Slot { + state: if vault { State::Up } else { State::Absent }, + used: 0, + }, + over: false, + } + } + + /// 서비스의 상태를 주는 함수입니다. + pub const fn state(&self, id: Id) -> State { + match id { + Id::Terminal => self.term.state, + Id::Vault => self.vault.state, + } + } + + /// 서비스를 지금까지 다시 띄우기로 한 횟수를 주는 함수입니다. + pub const fn restarts(&self, id: Id) -> u32 { + match id { + Id::Terminal => self.term.used, + Id::Vault => self.vault.used, + } + } + + /// 감독할 서비스가 하나도 남지 않았는지 주는 함수입니다. + pub const fn is_over(&self) -> bool { + !matches!(self.term.state, State::Up | State::Wait(_)) + && !matches!(self.vault.state, State::Up | State::Wait(_)) + } + + /// 폴 한 번을 처리하는 함수입니다. 감독할 서비스가 남아 있으면 `true` + /// + /// 터미널을 먼저 봅니다. 터미널이 이 폴에서 완전히 내려가면 볼트도 같은 + /// 폴에서 내립니다. 감독이 끝나면 그 줄을 한 번만 냅니다. + /// + /// # Arguments + /// `host` - 묻고 시킬 상대 + pub fn poll(&mut self, host: &mut impl Host) -> bool { + self.step(Id::Terminal, host); + if matches!(self.term.state, State::Down(_)) { + match self.vault.state { + // 볼트를 부를 수 있는 태스크가 없음: 키를 남기지 않음 + State::Up => { + host.retire(Id::Vault); + host.line(Line::Stopped); + self.vault.state = State::Down(Why::NoTerminal); + } + // 이미 회수하고 지운 자리 + State::Wait(_) => { + host.line(Line::NotAgain(Id::Vault, Why::NoTerminal)); + self.vault.state = State::Down(Why::NoTerminal); + } + State::Absent | State::Down(_) => {} + } + } else { + self.step(Id::Vault, host); + } + if self.is_over() && !self.over { + self.over = true; + host.line(Line::Over); + } + !self.is_over() + } + + fn slot(&mut self, id: Id) -> &mut Slot { + match id { + Id::Terminal => &mut self.term, + Id::Vault => &mut self.vault, + } + } + + /// 다시 띄워도 되는지 묻는 함수입니다. 터미널만 입력 경로를 묻습니다. + fn wanted(id: Id, host: &mut impl Host) -> bool { + match id { + Id::Terminal => host.input_present(), + Id::Vault => true, + } + } + + fn rebuild(&mut self, id: Id, host: &mut impl Host) { + host.rebuild(id); + host.line(Line::Started(id)); + self.slot(id).state = State::Up; + } + + fn down(&mut self, id: Id, why: Why, host: &mut impl Host) { + host.line(Line::NotAgain(id, why)); + self.slot(id).state = State::Down(why); + } + + /// 서비스 하나의 폴 한 번을 처리하는 함수입니다. + fn step(&mut self, id: Id, host: &mut impl Host) { + let limits = self.limits; + let Slot { state, used } = *self.slot(id); + match state { + State::Absent | State::Down(_) => {} + State::Up => { + if !host.ended(id) { + return; + } + // 끝난 것은 다시 띄우든 아니든 회수함 + host.retire(id); + if !Self::wanted(id, host) { + return self.down(id, Why::NoInput, host); + } + let Some(&wait) = limits.backoff.get(used as usize) else { + return self.down(id, Why::Spent, host); + }; + // 횟수는 다시 띄우기로 정한 때에 셈(성공했을 때가 아님) + self.slot(id).used = used + 1; + host.line(Line::Restart { + id, + restart: used + 1, + of: limits.backoff.len() as u32, + ticks: wait.saturating_mul(limits.period), + }); + if wait == 0 { + self.rebuild(id, host); + } else { + self.slot(id).state = State::Wait(wait); + } + } + State::Wait(n) if n > 1 => self.slot(id).state = State::Wait(n - 1), + State::Wait(_) => { + // 기다리는 동안 입력 경로가 꺼졌을 수 있으므로 다시 물음 + if Self::wanted(id, host) { + self.rebuild(id, host); + } else { + self.down(id, Why::NoInput, host); + } + } + } + } +} diff --git a/userspace/k0-sup/src/tests.rs b/userspace/k0-sup/src/tests.rs new file mode 100644 index 0000000..5da66be --- /dev/null +++ b/userspace/k0-sup/src/tests.rs @@ -0,0 +1,569 @@ +use super::*; + +/// 폴 사이에 서비스가 한 일과, 감독자가 시킨 일을 기록하는 모형입니다. +#[derive(Default)] +struct Mock { + /// 지금 끝나 있는 서비스 + term_ended: bool, + vault_ended: bool, + /// 입력 경로가 없음 + no_input: bool, + /// 불린 순서대로의 기록 + log: Vec, + lines: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Call { + Ended(Id), + Input, + Retire(Id), + Rebuild(Id), +} + +impl Host for Mock { + fn ended(&mut self, id: Id) -> bool { + self.log.push(Call::Ended(id)); + match id { + Id::Terminal => self.term_ended, + Id::Vault => self.vault_ended, + } + } + + fn input_present(&mut self) -> bool { + self.log.push(Call::Input); + !self.no_input + } + + fn retire(&mut self, id: Id) { + self.log.push(Call::Retire(id)); + } + + fn rebuild(&mut self, id: Id) { + self.log.push(Call::Rebuild(id)); + // 다시 만든 태스크는 살아 있음 + match id { + Id::Terminal => self.term_ended = false, + Id::Vault => self.vault_ended = false, + } + } + + fn line(&mut self, line: Line) { + self.lines.push(line); + } +} + +impl Mock { + fn count(&self, call: Call) -> usize { + self.log.iter().filter(|c| **c == call).count() + } + + /// 지금까지의 기록을 비우고 돌려줌 + fn take(&mut self) -> (Vec, Vec) { + (std::mem::take(&mut self.log), std::mem::take(&mut self.lines)) + } +} + +fn text(line: Line) -> String { + let mut s = String::new(); + line.write(|piece| s.push_str(piece)); + s +} + +const T: Id = Id::Terminal; +const V: Id = Id::Vault; + +#[test] +fn a_service_that_stays_up_is_left_alone() { + let mut sup = Supervisor::new(LIMITS, true); + let mut m = Mock::default(); + for _ in 0..1000 { + assert!(sup.poll(&mut m)); + } + // 폴마다 끝났는지만 물음. 회수도, 다시 만들기도, 줄도, 입력 질문도 없음 + assert_eq!(m.log.len(), 2000); + assert_eq!((m.count(Call::Ended(T)), m.count(Call::Ended(V))), (1000, 1000)); + assert!(m.lines.is_empty()); + assert_eq!((sup.state(T), sup.state(V)), (State::Up, State::Up)); + assert_eq!((sup.restarts(T), sup.restarts(V)), (0, 0)); +} + +#[test] +fn an_ended_service_is_retired_at_once_and_rebuilt_after_its_backoff() { + for id in [T, V] { + let mut sup = Supervisor::new(Limits { backoff: &[3], period: 2 }, true); + let mut m = Mock::default(); + let other = if id == T { V } else { T }; + match id { + Id::Terminal => m.term_ended = true, + Id::Vault => m.vault_ended = true, + } + // 끝난 것을 본 폴: 그 자리에서 회수하고 기다리기 시작함 + assert!(sup.poll(&mut m)); + let (log, lines) = m.take(); + assert!(log.contains(&Call::Retire(id)) && !log.contains(&Call::Rebuild(id))); + assert!(!log.contains(&Call::Retire(other))); + assert_eq!(lines, [Line::Restart { id, restart: 1, of: 1, ticks: 6 }]); + assert_eq!(sup.state(id), State::Wait(3)); + // 그 뒤 두 번의 폴에서는 그 서비스에 대해 아무 일도 하지 않음 + for left in [2, 1] { + assert!(sup.poll(&mut m)); + let (log, lines) = m.take(); + assert_eq!(log, [Call::Ended(other)]); + assert!(lines.is_empty()); + assert_eq!(sup.state(id), State::Wait(left)); + } + // 세 번째 폴에서 다시 만듦 + assert!(sup.poll(&mut m)); + let (log, lines) = m.take(); + assert_eq!(log.iter().filter(|c| **c == Call::Rebuild(id)).count(), 1); + assert!(!log.contains(&Call::Retire(id))); + assert_eq!(lines, [Line::Started(id)]); + assert_eq!((sup.state(id), sup.restarts(id)), (State::Up, 1)); + // 다시 만든 것은 다시 폴마다 물음 + assert!(sup.poll(&mut m)); + assert!(m.log.contains(&Call::Ended(id))); + } +} + +#[test] +fn the_backoff_grows_with_every_restart() { + let mut sup = Supervisor::new(LIMITS, false); + let mut m = Mock::default(); + let mut waits = Vec::new(); + for _ in 0..3 { + m.term_ended = true; + let mut polls = 0; + // 끝난 것을 본 폴을 0으로 세고, 다시 만든 폴까지의 거리를 잼 + while m.count(Call::Rebuild(T)) == 0 { + assert!(sup.poll(&mut m)); + polls += 1; + } + waits.push(polls - 1); + m.take(); + } + assert_eq!(waits, [1, 4, 16]); + assert_eq!(sup.restarts(T), 3); + // 줄에 적는 수는 폴 수에 주기를 곱한 틱 수 + let mut sup = Supervisor::new(LIMITS, false); + let mut m = Mock::default(); + for want in [2, 8, 32] { + m.term_ended = true; + while m.count(Call::Rebuild(T)) == 0 { + sup.poll(&mut m); + } + let (_, lines) = m.take(); + let Line::Restart { ticks, of, .. } = lines[0] else { + panic!("the first line of a restart is {:?}", lines[0]) + }; + assert_eq!((ticks, of), (want, 3)); + } +} + +#[test] +fn the_budget_ends_in_a_final_state() { + let mut sup = Supervisor::new(Limits { backoff: &[1, 1], period: 2 }, false); + let mut m = Mock::default(); + for _ in 0..2 { + m.term_ended = true; + assert!(sup.poll(&mut m)); + assert!(sup.poll(&mut m)); + assert_eq!(sup.state(T), State::Up); + } + m.take(); + // 세 번째로 끝나면 회수는 하되 다시 띄우지 않고 감독이 끝남 + m.term_ended = true; + assert!(!sup.poll(&mut m)); + let (log, lines) = m.take(); + assert_eq!(log, [Call::Ended(T), Call::Retire(T), Call::Input]); + assert_eq!(lines, [Line::NotAgain(T, Why::Spent), Line::Over]); + assert_eq!((sup.state(T), sup.restarts(T)), (State::Down(Why::Spent), 2)); + assert!(sup.is_over()); +} + +#[test] +fn a_terminal_without_input_goes_down_without_using_budget() { + let mut sup = Supervisor::new(LIMITS, false); + let mut m = Mock { term_ended: true, no_input: true, ..Mock::default() }; + assert!(!sup.poll(&mut m)); + let (log, lines) = m.take(); + // 끝난 것은 회수하고, 그 뒤에 입력 경로를 물음 + assert_eq!(log, [Call::Ended(T), Call::Retire(T), Call::Input]); + assert_eq!(lines, [Line::NotAgain(T, Why::NoInput), Line::Over]); + assert_eq!((sup.state(T), sup.restarts(T)), (State::Down(Why::NoInput), 0)); +} + +#[test] +fn the_input_is_asked_again_before_the_rebuild() { + let mut sup = Supervisor::new(Limits { backoff: &[4], period: 2 }, false); + let mut m = Mock { term_ended: true, ..Mock::default() }; + assert!(sup.poll(&mut m)); + assert_eq!(m.count(Call::Input), 1); + // 기다리는 동안에는 묻지 않음 + for _ in 0..3 { + assert!(sup.poll(&mut m)); + } + assert_eq!(m.count(Call::Input), 1); + // 그사이 입력 경로가 꺼졌으면 다시 만들지 않음. 쓴 횟수는 되돌리지 않음 + m.no_input = true; + assert!(!sup.poll(&mut m)); + assert_eq!((m.count(Call::Input), m.count(Call::Rebuild(T))), (2, 0)); + assert_eq!(m.lines.last(), Some(&Line::Over)); + assert_eq!(m.lines[m.lines.len() - 2], Line::NotAgain(T, Why::NoInput)); + assert_eq!((sup.state(T), sup.restarts(T)), (State::Down(Why::NoInput), 1)); +} + +#[test] +fn the_input_is_not_asked_while_the_terminal_is_up() { + // 살아 있는 터미널이 받을 입력을 감독자가 가져가면 안 됨 + let mut sup = Supervisor::new(LIMITS, true); + let mut m = Mock::default(); + for round in 0..200 { + // 볼트만 가끔 끝남 + m.vault_ended = round % 50 == 7; + sup.poll(&mut m); + } + assert_eq!(sup.state(T), State::Up); + assert!(m.count(Call::Retire(V)) >= 3); + assert_eq!(m.count(Call::Input), 0); +} + +#[test] +fn down_ignores_everything() { + let mut sup = Supervisor::new(Limits { backoff: &[], period: 2 }, true); + let mut m = Mock { term_ended: true, ..Mock::default() }; + assert!(!sup.poll(&mut m)); + m.take(); + // 내려간 뒤에는 무엇이 어떻게 되든 묻지도 시키지도 알리지도 않음 + for i in 0..100 { + m.term_ended = i % 2 == 0; + m.vault_ended = i % 3 == 0; + m.no_input = i % 5 == 0; + assert!(!sup.poll(&mut m)); + } + assert!(m.log.is_empty() && m.lines.is_empty()); + assert!(matches!((sup.state(T), sup.state(V)), (State::Down(_), State::Down(_)))); +} + +#[test] +fn the_two_services_keep_separate_budgets() { + let mut sup = Supervisor::new(Limits { backoff: &[1, 1, 1], period: 2 }, true); + let mut m = Mock::default(); + // 볼트만 상한까지 다시 띄움 + for _ in 0..3 { + m.vault_ended = true; + assert!(sup.poll(&mut m)); + assert!(sup.poll(&mut m)); + } + assert_eq!((sup.restarts(V), sup.restarts(T)), (3, 0)); + m.vault_ended = true; + assert!(sup.poll(&mut m), "the terminal is still supervised"); + assert_eq!(sup.state(V), State::Down(Why::Spent)); + assert_eq!(m.lines.last(), Some(&Line::NotAgain(V, Why::Spent))); + // 터미널의 한도는 그대로 남아 있음 + for used in 1..=3 { + m.term_ended = true; + assert!(sup.poll(&mut m)); + assert!(sup.poll(&mut m)); + assert_eq!((sup.state(T), sup.restarts(T)), (State::Up, used)); + } +} + +#[test] +fn a_living_vault_is_stopped_and_erased_when_the_terminal_is_down_for_good() { + // 터미널이 한도를 다 쓴 경우와 입력 경로가 없어진 경우 + for no_input in [false, true] { + let mut sup = Supervisor::new(Limits { backoff: &[], period: 2 }, true); + let mut m = Mock { term_ended: true, no_input, ..Mock::default() }; + assert!(!sup.poll(&mut m)); + let (log, lines) = m.take(); + // 같은 폴에서 볼트를 내리고 지움. 볼트에게는 끝났는지 묻지도 않음 + assert_eq!(log, [Call::Ended(T), Call::Retire(T), Call::Input, Call::Retire(V)]); + let why = if no_input { Why::NoInput } else { Why::Spent }; + assert_eq!(lines, [Line::NotAgain(T, why), Line::Stopped, Line::Over]); + assert_eq!(sup.state(V), State::Down(Why::NoTerminal)); + assert!(sup.is_over()); + } +} + +#[test] +fn a_vault_that_waits_is_not_rebuilt_when_the_terminal_goes_down() { + let mut sup = Supervisor::new(Limits { backoff: &[5], period: 2 }, true); + let mut m = Mock { vault_ended: true, ..Mock::default() }; + assert!(sup.poll(&mut m)); + assert_eq!(sup.state(V), State::Wait(5)); + m.take(); + // 볼트가 기다리는 동안 터미널이 한 번 다시 뜨고, 또 끝나 한도를 다 씀 + m.term_ended = true; + assert!(sup.poll(&mut m)); + for _ in 0..5 { + sup.poll(&mut m); + } + assert_eq!((sup.state(T), sup.state(V)), (State::Up, State::Up)); + m.take(); + m.vault_ended = true; + assert!(sup.poll(&mut m)); + assert_eq!(sup.state(V), State::Down(Why::Spent)); + m.take(); + let mut sup = Supervisor::new(Limits { backoff: &[5], period: 2 }, true); + m.vault_ended = true; + m.term_ended = false; + assert!(sup.poll(&mut m)); + m.take(); + // 이번에는 볼트가 기다리는 중에 터미널이 완전히 내려감 + m.term_ended = true; + m.no_input = true; + assert!(!sup.poll(&mut m)); + let (log, lines) = m.take(); + // 볼트는 이미 회수하고 지운 자리라 다시 회수하지 않고, 다시 만들지도 않음 + assert_eq!(log, [Call::Ended(T), Call::Retire(T), Call::Input]); + assert_eq!( + lines, + [Line::NotAgain(T, Why::NoInput), Line::NotAgain(V, Why::NoTerminal), Line::Over] + ); + assert_eq!(sup.state(V), State::Down(Why::NoTerminal)); +} + +#[test] +fn a_vault_that_ended_is_always_retired() { + // 한도가 없어도, 터미널이 같은 폴에서 내려가도, 끝난 볼트의 자리는 회수됨 + let mut sup = Supervisor::new(Limits { backoff: &[], period: 2 }, true); + let mut m = Mock { vault_ended: true, ..Mock::default() }; + assert!(sup.poll(&mut m)); + assert_eq!(m.count(Call::Retire(V)), 1); + assert_eq!(m.lines, [Line::NotAgain(V, Why::Spent)]); + + let mut sup = Supervisor::new(Limits { backoff: &[], period: 2 }, true); + let mut m = Mock { vault_ended: true, term_ended: true, ..Mock::default() }; + assert!(!sup.poll(&mut m)); + assert_eq!(m.count(Call::Retire(V)), 1); + assert_eq!(m.count(Call::Rebuild(V)), 0); +} + +#[test] +fn supervision_is_over_once_and_only_when_everything_is_down() { + let mut sup = Supervisor::new(Limits { backoff: &[2], period: 2 }, true); + let mut m = Mock::default(); + // 기다리는 서비스가 있으면 끝난 것이 아님 + m.term_ended = true; + assert!(sup.poll(&mut m)); + assert!(!sup.is_over() && !m.lines.contains(&Line::Over)); + assert!(sup.poll(&mut m)); + assert!(sup.poll(&mut m)); + assert_eq!(sup.state(T), State::Up); + m.term_ended = true; + assert!(!sup.poll(&mut m)); + for _ in 0..10 { + assert!(!sup.poll(&mut m)); + } + assert_eq!(m.lines.iter().filter(|l| **l == Line::Over).count(), 1); + assert_eq!(m.lines.last(), Some(&Line::Over)); +} + +#[test] +fn an_image_without_a_vault_supervises_only_the_terminal() { + let mut sup = Supervisor::new(LIMITS, false); + let mut m = Mock { vault_ended: true, ..Mock::default() }; + for _ in 0..50 { + assert!(sup.poll(&mut m)); + } + assert_eq!(sup.state(V), State::Absent); + assert!(m.log.iter().all(|c| *c == Call::Ended(T))); + assert!(m.lines.is_empty()); + m.term_ended = true; + m.no_input = true; + assert!(!sup.poll(&mut m)); + assert_eq!(m.lines, [Line::NotAgain(T, Why::NoInput), Line::Over]); + assert!(m.log.iter().all(|c| !matches!(c, Call::Retire(Id::Vault) | Call::Rebuild(Id::Vault)))); +} + +#[test] +fn a_backoff_of_zero_rebuilds_in_the_same_poll() { + // 부팅 자가 시험이 쓰는 한도: 기다림 없이 두 번 + let mut sup = Supervisor::new(Limits { backoff: &[0, 0], period: 2 }, true); + let mut m = Mock::default(); + for (id, restart) in [(T, 1), (V, 1), (T, 2), (V, 2)] { + match id { + Id::Terminal => m.term_ended = true, + Id::Vault => m.vault_ended = true, + } + assert!(sup.poll(&mut m)); + let (log, lines) = m.take(); + let at = |c: Call| log.iter().position(|x| *x == c).unwrap(); + assert!(at(Call::Ended(id)) < at(Call::Retire(id)) && at(Call::Retire(id)) < at(Call::Rebuild(id))); + assert_eq!(lines, [Line::Restart { id, restart, of: 2, ticks: 0 }, Line::Started(id)]); + assert_eq!((sup.state(id), sup.restarts(id)), (State::Up, restart)); + } +} + +struct Rng(u64); + +impl Rng { + fn below(&mut self, n: u64) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 % n + } +} + +#[test] +fn no_history_gives_more_rebuilds_than_the_budget() { + let tables: [&'static [u32]; 5] = [&[], &[0], &[1, 4, 16], &[0, 0, 0, 0], &[2, 1, 3, 1, 2]]; + let mut rng = Rng(0x243F_6A88_85A3_08D3); + let (mut rebuilds, mut overs) = (0, 0); + for round in 0..4000 { + let backoff = tables[round % tables.len()]; + let vault = rng.below(4) != 0; + let mut sup = Supervisor::new(Limits { backoff, period: 2 }, vault); + let mut m = Mock::default(); + let mut alive = true; + for _ in 0..(20 + rng.below(200)) { + // 살아 있는 서비스는 아무 때나 끝나고, 입력 경로는 가끔 꺼졌다 켜짐 + if rng.below(3) == 0 { + m.term_ended = true; + } + if rng.below(4) == 0 { + m.vault_ended = true; + } + m.no_input = rng.below(40) == 0; + let before = (sup.state(T), sup.state(V)); + let more = sup.poll(&mut m); + assert_eq!(more, !sup.is_over()); + // 한 번 끝난 감독은 다시 살아나지 않음 + assert!(alive || !more, "supervision came back to life"); + alive = more; + // 내려간 서비스는 내려간 채로 있음 + for (id, was) in [(T, before.0), (V, before.1)] { + if matches!(was, State::Down(_) | State::Absent) { + assert_eq!(sup.state(id), was); + } + } + } + let budget = backoff.len(); + for id in [T, V] { + let built = m.count(Call::Rebuild(id)); + assert!(built <= budget, "{built} rebuilds of {id:?} with a budget of {budget}"); + assert!(built <= sup.restarts(id) as usize && sup.restarts(id) as usize <= budget); + // 회수는 시작한 횟수를 넘지 않음(처음 시작 한 번과 다시 만든 횟수) + assert!(m.count(Call::Retire(id)) <= built + 1); + rebuilds += built; + } + if !vault { + assert!(m.log.iter().all(|c| !matches!(c, Call::Ended(Id::Vault) | Call::Retire(Id::Vault)))); + } + // 볼트는 터미널이 내려간 뒤로는 다시 만들어지지 않음 + if let Some(down) = m.lines.iter().position(|l| matches!(l, Line::NotAgain(Id::Terminal, _))) { + assert!(!m.lines[down..].contains(&Line::Started(V))); + } + let over = m.lines.iter().filter(|l| **l == Line::Over).count(); + assert_eq!(over, usize::from(sup.is_over())); + overs += over; + } + assert!(rebuilds > 3_000 && overs > 1_000, "only {rebuilds} rebuilds and {overs} ends"); +} + +/// 부팅 시험 스크립트(`tools/qemu-boot-test.sh`)가 실패로 읽는 낱말들입니다. +/// 그 스크립트의 `fail_re`와 같아야 합니다. +const FAIL_WORDS: [&str; 14] = [ + "root: FAIL", + "k0: EXCEPTION", + "k0: PANIC", + "k0: FATAL", + "k0: UNEXPECTED", + "rejected", + "failed", + "check fail", + "k0: all tasks", + "corrupt", + "overflow", + "no frame window", + "too many root task segments", + "k0-loader: refused", +]; + +fn every_line() -> Vec { + let mut all = vec![Line::Stopped, Line::Over]; + for id in [T, V] { + all.push(Line::Started(id)); + for why in [Why::NoInput, Why::Spent, Why::NoTerminal] { + all.push(Line::NotAgain(id, why)); + } + for (restart, of, ticks) in [(1, 3, 2), (2, 3, 8), (3, 3, 32), (1, 2, 0), (10, 4_294_967_295, 1_000_000)] { + all.push(Line::Restart { id, restart, of, ticks }); + } + } + all +} + +#[test] +fn no_line_looks_like_a_failure_to_the_boot_harness() { + for line in every_line() { + let s = text(line); + for word in FAIL_WORDS { + assert!(!s.contains(word), "{s:?} contains {word:?}"); + } + // 한 줄이고, 루트 태스크의 줄이며, 콘솔 필터가 바꾸지 않는 글자뿐임 + assert!(s.starts_with("root: ") && s.ends_with('\n'), "{s:?}"); + let body = &s[..s.len() - 1]; + assert!(body.bytes().all(|b| (0x20..=0x7E).contains(&b)), "{s:?}"); + assert!(body.len() <= 96, "{s:?} is too long for a log line"); + // 부팅 시험이 순서대로 찾는 줄의 머리와 겹치지 않음 + for marker in ["root: service started", "root: vault seeded", "root: vault has no seed", "root: terminal wiring"] { + assert!(!s.starts_with(marker), "{s:?} looks like {marker:?}"); + } + } +} + +#[test] +fn the_fail_words_match_the_boot_harness() { + let script = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../tools/qemu-boot-test.sh")) + .expect("the boot test script is readable"); + let line = script + .lines() + .find_map(|l| l.strip_prefix("fail_re='")) + .expect("the script defines fail_re"); + let words: Vec<&str> = line.trim_end_matches('\'').split('|').collect(); + assert_eq!(words, FAIL_WORDS); +} + +#[test] +fn the_lines_read_as_written_in_the_documents() { + assert_eq!( + text(Line::Restart { id: T, restart: 1, of: 3, ticks: 2 }), + "root: terminal ended, restart 1 of 3 after at least 2 ticks\n" + ); + assert_eq!( + text(Line::Restart { id: V, restart: 3, of: 3, ticks: 32 }), + "root: vault ended and erased, restart 3 of 3 after at least 32 ticks\n" + ); + assert_eq!(text(Line::Started(T)), "root: terminal started again\n"); + assert_eq!(text(Line::Started(V)), "root: vault started again without a key\n"); + assert_eq!( + text(Line::NotAgain(T, Why::NoInput)), + "root: terminal ended, no console input, not started again\n" + ); + assert_eq!( + text(Line::NotAgain(T, Why::Spent)), + "root: terminal ended, restart budget spent, not started again\n" + ); + assert_eq!( + text(Line::NotAgain(V, Why::Spent)), + "root: vault ended and erased, restart budget spent, not started again\n" + ); + assert_eq!( + text(Line::NotAgain(V, Why::NoTerminal)), + "root: vault ended and erased, no terminal, not started again\n" + ); + assert_eq!(text(Line::Stopped), "root: vault stopped and erased, no terminal\n"); + assert_eq!(text(Line::Over), "root: supervision over\n"); +} + +#[test] +fn numbers_are_written_in_decimal() { + for v in [0u32, 1, 9, 10, 11, 99, 100, 101, 4096, 65_535, 1_000_000, u32::MAX - 1, u32::MAX] { + let mut s = String::new(); + number(v, &mut |piece: &str| s.push_str(piece)); + assert_eq!(s, v.to_string()); + } +} diff --git a/userspace/k0-vault/src/server.rs b/userspace/k0-vault/src/server.rs index 52f5705..0cf2f5d 100644 --- a/userspace/k0-vault/src/server.rs +++ b/userspace/k0-vault/src/server.rs @@ -69,6 +69,23 @@ impl Vault { } } + /// 다시 시작된 볼트를 만드는 함수입니다. 시드도 키도 없이, 소거된 상태로 + /// 시작합니다. + /// + /// 감독자가 끝난 볼트의 자리에 볼트를 다시 띄울 때 씁니다. 부트 시드는 첫 + /// 볼트에게 한 번 넘어간 뒤 어디에도 남아 있지 않으므로 이 볼트는 키를 + /// 가질 길이 없습니다. 처음 상태([state::FRESH])로 두면 시드를 받을 수 있는 + /// 볼트로 보이므로, 운영자가 지운 볼트와 같은 상태로 시작해 시드와 키 + /// 생성을 볼트 스스로 거부하게 합니다. 자가 시험은 여기서도 돌리고, + /// 실패하면 오류 상태로 시작합니다. + pub fn retired() -> Self { + let mut v = Self::new(); + if v.state == state::FRESH { + v.state = state::ZEROIZED; + } + v + } + /// 요청 하나를 처리하는 함수입니다. /// /// 응답 레지스터 네 개를 전부 채워 돌려주고(쓰지 않는 값이 새지 않게), diff --git a/userspace/k0-vault/src/tests.rs b/userspace/k0-vault/src/tests.rs index 2cc8085..66b0da5 100644 --- a/userspace/k0-vault/src/tests.rs +++ b/userspace/k0-vault/src/tests.rs @@ -502,6 +502,55 @@ mod ed25519 { } } +#[test] +fn a_vault_started_again_takes_no_seed_and_makes_no_key() { + let mut v = Vault::retired(); + assert!(!v.holds_a_secret()); + // 운영자가 지운 볼트와 같은 상태로 보이고 자가 시험은 통과한 것으로 알림 + for badge in [ADMIN_BADGE, OPERATOR, SIGNER, READER] { + let (r, _) = call(&mut v, badge, request::STATUS, alg::NONE, &[]); + assert_eq!((r[0], status_word::state(r[1]), status_word::key_alg(r[1])), (status::OK, state::ZEROIZED, alg::NONE)); + assert_eq!(r[2], indicator::SELF_TEST_PASSED); + } + // 시드는 관리자가 넘겨도 받지 않음. 재료가 충분하다는 정보가 붙어 있어도 같음 + for info in [GOOD_INFO, 0, u64::MAX] { + let (r, _) = call(&mut v, ADMIN_BADGE, request::INIT, alg::NONE, &init_body([7; 32], info)); + assert_eq!(r[0], status::DENIED); + assert!(!v.holds_a_secret()); + } + // 키를 쓰는 연산은 역할마다 지워진 볼트의 답을 받음. 알고리즘이 없는 + // 이미지에서는 알고리즘 검사가 먼저라 지원하지 않는다는 답이 나옴 + let gone = if cfg!(feature = "ed25519") { status::ZEROIZED } else { status::UNSUPPORTED }; + for badge in [ADMIN_BADGE, OPERATOR] { + assert_eq!(call(&mut v, badge, request::KEYGEN, alg::ED25519, &[]).0[0], gone); + } + assert_eq!(call(&mut v, SIGNER, request::SIGN, alg::ED25519, b"m").0[0], gone); + for badge in [READER, OPERATOR, SIGNER] { + assert_eq!(call(&mut v, badge, request::PUBLIC_KEY, alg::ED25519, &[]).0[0], gone); + } + // 역할에 없는 연산은 여전히 거절이고, 지우는 것은 그대로 성공함 + assert_eq!(call(&mut v, ADMIN_BADGE, request::SIGN, alg::ED25519, b"m").0[0], status::DENIED); + assert_eq!(call(&mut v, OPERATOR, request::INIT, alg::NONE, &init_body([7; 32], GOOD_INFO)).0[0], status::DENIED); + assert_eq!(call(&mut v, OPERATOR, request::ZEROIZE, alg::NONE, &[]).0[0], status::OK); + assert_eq!(state_of(&mut v), state::ZEROIZED); + assert!(!v.holds_a_secret()); +} + +#[test] +fn a_fresh_vault_and_one_started_again_differ_only_in_the_state() { + let (mut fresh, mut again) = (Vault::new(), Vault::retired()); + assert_eq!(state_of(&mut fresh), state::FRESH); + assert_eq!(state_of(&mut again), state::ZEROIZED); + let word = |v: &mut Vault| call(v, READER, request::STATUS, alg::NONE, &[]).0; + let (a, b) = (word(&mut fresh), word(&mut again)); + assert_eq!((status_word::built(a[1]), a[2]), (status_word::built(b[1]), b[2])); + // 처음 상태의 볼트만 시드를 받음(알고리즘이 있는 이미지에서) + let body = init_body([7; 32], GOOD_INFO); + let took = call(&mut fresh, ADMIN_BADGE, request::INIT, alg::NONE, &body).0[0]; + assert_eq!(took, if cfg!(feature = "ed25519") { status::OK } else { status::UNSUPPORTED }); + assert_eq!(call(&mut again, ADMIN_BADGE, request::INIT, alg::NONE, &body).0[0], status::DENIED); +} + #[cfg(not(feature = "ed25519"))] #[test] fn without_an_algorithm_the_vault_takes_no_seed_and_serves_nothing() { diff --git a/userspace/root-task/Cargo.toml b/userspace/root-task/Cargo.toml index a9edf5e..6f5bcac 100644 --- a/userspace/root-task/Cargo.toml +++ b/userspace/root-task/Cargo.toml @@ -9,6 +9,7 @@ publish.workspace = true k0-abi = { path = "../../crates/k0-abi" } k0-vault = { path = "../k0-vault", optional = true } k0-term = { path = "../k0-term", optional = true } +k0-sup = { path = "../k0-sup", optional = true } # 키 볼트(서명 오라클)는 선택 기능입니다. `vault`는 서비스와 그 자가 검증을 # 넣고, 알고리즘은 따로 더합니다. 아무것도 기본으로 켜지지 않습니다. @@ -16,9 +17,10 @@ k0-term = { path = "../k0-term", optional = true } # `console-input`은 커널에 콘솔 입력 경로가 있다는 뜻이고(커널의 같은 이름 # feature가 넘김) 입력 시스템 콜의 자가 검증을 넣습니다. `terminal`은 운영자 # 터미널을 넣어 자가 검증 뒤에 서비스로 시작합니다. 볼트가 함께 있으면 -# 터미널이 볼트의 운영자 역할을 맡습니다. +# 터미널이 볼트의 운영자 역할을 맡습니다. 터미널이 든 이미지의 루트 태스크는 +# 서비스를 감독하므로 그 정책(`k0-sup`)도 함께 들어갑니다. [features] vault = ["dep:k0-vault", "k0-term?/vault"] vault-ed25519 = ["vault", "k0-vault/ed25519"] console-input = [] -terminal = ["console-input", "dep:k0-term"] +terminal = ["console-input", "dep:k0-term", "dep:k0-sup"] diff --git a/userspace/root-task/src/main.rs b/userspace/root-task/src/main.rs index 07090e1..5cf9b26 100644 --- a/userspace/root-task/src/main.rs +++ b/userspace/root-task/src/main.rs @@ -8,8 +8,10 @@ //! - 재분류(RETYPE)와 매핑(MAP / UNMAP) //! - 케이퍼빌리티 복사·이동·삭제·회수(CAP_COPY / CAP_MOVE / CAP_DELETE / //! CAP_REVOKE), 권한 축소와 배지, 회수한 untyped 메모리의 재사용 +//! - untyped 분할(UNTYPED_SPLIT): 잘라 받은 만큼만 쓸 수 있는 태스크, 슬랩을 +//! 회수해 같은 자리에 태스크를 다시 만드는 순서 //! - 태스크 생성(TCB_CONFIGURE / TCB_RESUME)과 스케줄러(양보, 종료, 타이머 -//! 선점) +//! 선점), 태스크가 끝났는지 묻기(TCB_STATUS) //! - 동기 랑데부 IPC(SEND / RECV / CALL / REPLY_RECV) //! - 폴트 격리(자식의 폴트와 FP/SIMD 트랩은 그 태스크만 종료, 스레드 //! 포인터는 태스크별 격리) @@ -44,7 +46,7 @@ mod service; mod timeslice; use k0_abi::bootinfo::slot; -use k0_abi::{bootinfo, err, ipc, obj, perm, rights, syscall}; +use k0_abi::{bootinfo, err, ipc, obj, perm, rights, syscall, tcb_status}; /// 재분류 검증에 쓰는 테스트 VA (이미지/스택/bootinfo와 겹치지 않는 구간) const TEST_VA: u64 = 0x2000_0000; @@ -206,12 +208,19 @@ fn put_hex(v: u64) { /// 검증 실패를 출력하고 태스크를 끝내는 함수입니다. 복귀하지 않습니다. /// +/// 루트 태스크 자신만 부릅니다. 격리된 태스크의 진입점은 static을 볼 수 없어 +/// 이 함수를 쓰지 않습니다. +/// /// # Arguments /// `step` - 실패한 검증 단계 이름 fn fail(step: &str) -> ! { put_str("root: FAIL "); put_str(step); put_str("\n"); + // 서비스의 볼트가 시드를 받은 뒤라면, 감독자 없이 키가 남지 않게 끝나기 + // 전에 볼트의 메모리를 지우기를 시도함 + #[cfg(all(feature = "terminal", feature = "vault"))] + service::scrub_on_failure(); sys1(syscall::EXIT, 1); loop { core::hint::spin_loop(); @@ -268,6 +277,12 @@ fn retype(ut: u64, kind: u64) -> i64 { } } +/// untyped에서 그래뉼 `granules`개짜리 자식 untyped를 잘라 `dest`에 넣는 +/// 함수입니다. +fn untyped_split(ut: u64, dest: u64, granules: u64) -> i64 { + sys(syscall::UNTYPED_SPLIT, [ut, granules, dest, 0, 0, 0]) as i64 +} + fn map_into(cap: i64, va: u64, p: u64, aspace: i64) -> i64 { sys(syscall::MAP, [cap as u64, va, p, aspace as u64, 0, 0]) as i64 } @@ -323,6 +338,26 @@ fn tcb_resume(tcb: i64) -> i64 { sys1(syscall::TCB_RESUME, tcb as u64) as i64 } +/// 태스크의 상태([tcb_status])를 묻는 함수입니다. 실패하면 음수 에러 +fn tcb_state(tcb: i64) -> i64 { + sys1(syscall::TCB_STATUS, tcb as u64) as i64 +} + +/// 태스크가 끝난 것으로 보일 때까지 양보하며 기다리는 함수입니다. +/// +/// 끝나기 전에는 살아 있다는 답만 나와야 합니다. 정해진 횟수 안에 끝나지 +/// 않거나 다른 답이 나오면 `false` +fn ends_soon(tcb: i64) -> bool { + for _ in 0..64 { + match tcb_state(tcb) { + tcb_status::ENDED => return true, + tcb_status::ALIVE => yield_now(), + _ => return false, + } + } + false +} + /// 시간 분할 표의 항목들을 PART_SET_TABLE의 레지스터 넷으로 싸는 함수입니다. /// /// 항목 i는 레지스터 i / 4의 비트 16 * (i % 4)부터 16비트이고 값은 @@ -1431,6 +1466,18 @@ fn test_sched_ipc_fault(b: &Boot) { let entry_exit = child_exit_entry as usize as u64; let (aspace, cnode) = (slot::ADDR_SPACE as i64, slot::CNODE as i64); + // 상태 묻기의 거부 경로, 그리고 자기 자신과 구성 전인 TCB의 상태 + let no_cap = alloc_slot() as i64; + check("status null slot", tcb_state(0) == err::BAD_SLOT); + check("status far slot", tcb_state(9999) == err::BAD_SLOT); + check("status empty slot", tcb_state(no_cap) == err::BAD_SLOT); + check( + "status wrong kind", + tcb_state(slot::CONSOLE as i64) == err::BAD_CAP && tcb_state(f) == err::BAD_CAP, + ); + check("status self", tcb_state(slot::TCB as i64) == tcb_status::ALIVE); + check("status unconfigured", tcb_state(tcb_spare) == tcb_status::NOT_STARTED); + // 거부 경로: 구성 전 재개, 잘못된 케이퍼빌리티, 스택 정렬 위반 check("resume unconfigured", tcb_resume(tcb_spare) == err::BAD_STATE); check( @@ -1455,6 +1502,7 @@ fn test_sched_ipc_fault(b: &Boot) { ); // 거부된 구성은 TCB를 건드리지 않았어야 함 check("still unconfigured", tcb_resume(tcb_spare) == err::BAD_STATE); + check("status still unconfigured", tcb_state(tcb_spare) == tcb_status::NOT_STARTED); // 실행 중인 자신의 TCB는 재구성할 수 없음 check( "configure self", @@ -1462,6 +1510,7 @@ fn test_sched_ipc_fault(b: &Boot) { ); // 구성된 적 없는 TCB도 삭제할 수 있음 check("delete unconfigured tcb", cap_delete(tcb_spare) == 0); + check("status deleted spare", tcb_state(tcb_spare) == err::BAD_SLOT); // 유한 태스크: 실행 -> 목표 도달 -> EXIT -> 루트로 복귀 check( @@ -1472,11 +1521,16 @@ fn test_sched_ipc_fault(b: &Boot) { "configure twice", thread_configure(tcb_exit, entry_exit, sp_exit) == err::BAD_STATE, ); + // 구성만 된 태스크는 아직 시작 전이고, 재개하면 살아 있음 + check("status configured", tcb_state(tcb_exit) == tcb_status::NOT_STARTED); check("resume tcb exit", tcb_resume(tcb_exit) == 0); + check("status resumed", tcb_state(tcb_exit) == tcb_status::ALIVE); check("resume twice", tcb_resume(tcb_exit) == err::BAD_STATE); while EXIT_COUNTER.load(Ordering::Relaxed) != CHILD_EXIT_TARGET { yield_now(); } + // EXIT로 끝난 태스크는 끝난 것으로 보이고, 거듭 물어도 같음 + check("status exited", ends_soon(tcb_exit) && tcb_state(tcb_exit) == tcb_status::ENDED); put_str("root: child exit test pass\n"); // 엔드포인트: 재분류, 커널 오브젝트라 매핑 불가, 빈 큐 비대기 즉시 복귀 @@ -1528,6 +1582,8 @@ fn test_sched_ipc_fault(b: &Boot) { // 수신자 선행 랑데부: 서버가 RECV에서 대기 중일 때 즉시 전달. // NONBLOCK은 상대가 준비돼 있으면 즉시 성공해야 함 let m2 = [0x5555, 0x6666, 0x7777, 0x8888]; + // 수신을 기다리는 태스크도 살아 있다고만 보임 + check("status blocked recv", tcb_state(tcb_srv) == tcb_status::ALIVE); check("send to waiting nb", send(ep, nb, m2).status == 0); while SRV_COUNT.load(Ordering::Relaxed) < 2 { yield_now(); @@ -1610,6 +1666,8 @@ fn test_sched_ipc_fault(b: &Boot) { check("held call data", slot.load(Ordering::Relaxed) == v); } check("client still held", CLIENT_STATUS.load(Ordering::Relaxed) == 1); + // 응답을 기다리는 태스크도 마찬가지 + check("status blocked reply", tcb_state(tcb_cl) == tcb_status::ALIVE); // 자격 덮어쓰기: 루트의 CALL이 자격을 덮으면 이전 호출자(클라이언트)는 // NO_REPLY로 깨어나고 루트는 정상 응답을 받아야 함 @@ -1627,6 +1685,7 @@ fn test_sched_ipc_fault(b: &Boot) { let r = call(ep, 0, [0xE0E0, 0, 0, 0]); check("call no reply", r.status == err::NO_REPLY); check("no reply count", SRV_COUNT.load(Ordering::Relaxed) == 8); + check("status server exited", tcb_state(tcb_srv) == tcb_status::ENDED); put_str("root: ipc tests pass\n"); @@ -1669,6 +1728,9 @@ fn test_sched_ipc_fault(b: &Boot) { check("fault child killed", FAULT_SURVIVED.load(Ordering::Relaxed) == 0); check("root tpidr after kill", get_tpidr() == ROOT_TPIDR); check("dead tcb resume", tcb_resume(tcb_fault) == err::BAD_STATE); + // 재개가 거부되는 것만으로는 죽은 태스크와 도는 태스크가 구별되지 않음. + // 폴트로 끝난 태스크는 끝난 것으로 보여야 함 + check("status after fault", tcb_state(tcb_fault) == tcb_status::ENDED); // FP/SIMD 명령은 CPACR_EL1 트랩으로 그 태스크만 종료돼야 함 check( @@ -1683,13 +1745,19 @@ fn test_sched_ipc_fault(b: &Boot) { yield_now(); } check("fp child killed", FAULT_SURVIVED.load(Ordering::Relaxed) == 0); + check("status after fp trap", tcb_state(tcb_fp) == tcb_status::ENDED); set_tpidr(0); // 종료된 태스크의 TCB를 삭제해도 시스템은 그대로여야 하고, 삭제된 // 케이퍼빌리티는 더 쓸 수 없음 check("delete dead tcb", cap_delete(tcb_fault) == 0); check("deleted tcb gone", tcb_resume(tcb_fault) == err::BAD_SLOT); + check("status deleted tcb", tcb_state(tcb_fault) == err::BAD_SLOT); put_str("root: fault isolation tests pass\n"); + // 상태 묻기의 검사는 위의 태스크들이 그 상태에 있던 자리마다 들어 있음. + // 이 호출은 아무것도 바꾸지 않으므로 루트는 여전히 살아 있다고 보임 + check("status self again", tcb_state(slot::TCB as i64) == tcb_status::ALIVE); + put_str("root: tcb status tests pass\n"); // 양보 없이 도는 태스크가 타이머에 끊기는지, 그리고 틱 사이에 CPU를 받은 // 태스크가 처음 맞는 틱을 넘기는지. 앞선 검증의 태스크는 모두 종료됐으므로 @@ -1741,17 +1809,19 @@ impl Iso { false } - /// 격리된 태스크를 만들어 실행 대기 상태로 만드는 함수입니다. + /// 격리된 태스크를 만들어 구성까지만 해 두는 함수입니다. /// /// 새 CNode를 만들어 `caps`의 (원본 슬롯, 권한 마스크, 배지)를 1번 슬롯부터 - /// 차례로 복사해 넣고, 주소 공간에 스택 한 장을 매핑한 뒤 TCB를 구성해 - /// 재개합니다. 태스크가 쥐는 권한은 그 CNode에 든 것이 전부입니다. + /// 차례로 복사해 넣고, 주소 공간에 스택 한 장을 매핑한 뒤 TCB를 구성합니다. + /// 재개는 하지 않으므로, 태스크가 돌기 전에 그 CNode에 더 넣어 줄 것이 + /// 있을 때 씁니다. 태스크가 쥐는 권한은 그 CNode에 든 것이 전부입니다. + /// 스택, CNode, TCB 순으로 그래뉼 셋을 씁니다. /// /// # Arguments /// `entry` - 진입점 /// `arg` - 태스크가 x0으로 받을 값 /// `caps` - CNode에 넣어 줄 케이퍼빌리티들 - fn spawn(&self, entry: u64, arg: u64, caps: &[(i64, u64, u64)]) -> Confined { + fn build(&self, entry: u64, arg: u64, caps: &[(i64, u64, u64)]) -> Confined { let index = NEXT_STACK.fetch_add(1, Ordering::Relaxed); check("iso stack budget", index < ISO_STACKS); let stack_va = ISO_STACK_VA + index * ISO_STACK_STEP; @@ -1771,9 +1841,20 @@ impl Iso { "iso configure", tcb_configure(tcb, entry, stack_va + self.fs, self.aspace, cnode, arg) == 0, ); - check("iso resume", tcb_resume(tcb) == 0); Confined { tcb, cnode } } + + /// 격리된 태스크를 만들어 실행 대기 상태로 만드는 함수입니다. + /// + /// # Arguments + /// `entry` - 진입점 + /// `arg` - 태스크가 x0으로 받을 값 + /// `caps` - CNode에 넣어 줄 케이퍼빌리티들 + fn spawn(&self, entry: u64, arg: u64, caps: &[(i64, u64, u64)]) -> Confined { + let t = self.build(entry, arg, caps); + check("iso resume", tcb_resume(t.tcb) == 0); + t + } } /// 받을 메시지가 없는 상태가 여러 번의 양보 뒤에도 유지되는지 확인하는 @@ -1924,6 +2005,8 @@ fn test_isolation(b: &Boot) { check("violator arrived", iso.wait_pulse(PULSE_VIOLATOR + kind)); check("violator stopped", stays_silent(q)); check("violator did not continue", iso.pulse() == PULSE_VIOLATOR + kind); + // 폴트로 끝났든 모르는 시스템 콜로 끝났든 끝난 것으로 보임 + check("violator ended", tcb_state(v.tcb) == tcb_status::ENDED); check("violator cleanup", cap_delete(v.tcb) == 0); } // 읽기 전용 공유 페이지는 쓰이지 않았어야 함 @@ -1942,6 +2025,7 @@ fn test_isolation(b: &Boot) { pulse_view, }; test_timeouts(&timed_iso, q); + test_split(&timed_iso, q, b); // CNode 회수: 태스크에 묶인 케이퍼빌리티 공간이 사라지면 그 태스크는 // 종료됨. 송신이 거부될 뿐 계속 실행된다면 pulse가 계속 바뀜 @@ -1954,6 +2038,7 @@ fn test_isolation(b: &Boot) { check("beat silent after cnode revoke", stays_silent(q)); check("beat stopped by cnode revoke", iso.pulse() == frozen); check("beat tcb is dead", tcb_resume(t.tcb) == err::BAD_STATE); + check("beat tcb ended", tcb_state(t.tcb) == tcb_status::ENDED); // 자기 TCB의 원본을 스스로 삭제: 시스템 콜 도중에 호출자가 종료되는 경로 let destruct = self_destruct_entry as usize as u64; @@ -1981,6 +2066,7 @@ fn test_isolation(b: &Boot) { check("beat silent after aspace delete", stays_silent(q)); check("beat stopped by aspace delete", iso.pulse() == frozen); check("beat 2 tcb is dead", tcb_resume(t.tcb) == err::BAD_STATE); + check("beat 2 tcb ended", tcb_state(t.tcb) == tcb_status::ENDED); check( "aspace cap gone", map_into(shared_ro, ISO_SHARED_VA + fs, perm::RO, aspace) == err::BAD_SLOT, @@ -2049,6 +2135,187 @@ fn test_isolation(b: &Boot) { put_str("root: revocation tests pass\n"); } +/// 분할 검증이 쓰는 크기(그래뉼 수)입니다. 슬랩에서 주소 공간과 테이블 셋, +/// 스택, CNode, TCB가 나가고(뼈대), 예산은 태스크에게 넘어갑니다. +const SLAB_GRANULES: u64 = 24; +const SKELETON_GRANULES: u64 = 7; +const BUDGET_GRANULES: u64 = 8; +/// 예산만 받은 태스크가 통과해야 하는 검사의 비트맵 +const CAPPED_ALL: u64 = (1 << 13) - 1; + +/// 잘라 받은 untyped 하나만 쥔 태스크의 진입점입니다. +/// +/// 1번 슬롯은 보고용 엔드포인트(송신만), 2번 슬롯은 그래뉼 여덟 개짜리 +/// untyped입니다. 받은 만큼만 오브젝트가 나오는지, 자기 것을 회수하고 다시 +/// 자를 수 있는지를 스스로 확인해 비트맵으로 보고합니다. static은 쓰지 +/// 않습니다. 보고한 뒤에는 응답을 기다리는 채로 있다가 루트가 슬랩을 회수할 +/// 때 종료됩니다. +extern "C" fn capped_entry(_arg: u64) -> ! { + let (ep, ut) = (1, 2); + let mut ok = 0u64; + let mut bit = 1u64; + let mut note = |pass: bool| { + if pass { + ok |= bit; + } + bit <<= 1; + }; + // 받은 그래뉼 수만큼만 오브젝트가 나옴 + let mut made = 0; + while made < 32 && retype_at(ut, obj::FRAME, 3 + made) == 0 { + made += 1; + } + note(made == BUDGET_GRANULES); + note(retype_at(ut, obj::FRAME, 3 + made) == err::EXHAUSTED); + note(untyped_split(ut, 3 + made, 1) == err::EXHAUSTED); + // 자기 것을 회수하면 자기에게 돌아옴 + note(cap_revoke(ut as i64) == 0); + note(cap_delete(3) == err::BAD_SLOT); + note(untyped_split(ut, 3, 0) == err::BAD_SIZE); + note(untyped_split(ut, 3, BUDGET_GRANULES + 1) == err::EXHAUSTED); + // 전부를 자식에게 주면 자기에게는 남는 것이 없음 + note(untyped_split(ut, 3, BUDGET_GRANULES) == 0); + note(untyped_split(ut, 4, 1) == err::EXHAUSTED); + // 자식을 다시 잘라도 나오는 오브젝트의 합은 그대로임 + note(untyped_split(3, 4, 1) == 0); + note(retype_at(4, obj::TCB, 5) == 0); + note(retype_at(4, obj::TCB, 6) == err::EXHAUSTED); + let mut more = 0; + while more < 32 && retype_at(3, obj::ENDPOINT, 6 + more) == 0 { + more += 1; + } + note(more == BUDGET_GRANULES - 1); + call(ep, 0, [ok, made, more, 0]); + loop { + yield_now(); + } +} + +/// untyped 분할을 검증하는 함수입니다. +/// +/// 가장 큰 untyped에서 슬랩을 자르고, 슬랩 안에 태스크의 뼈대(주소 공간, 스택, +/// CNode, TCB)를 만든 뒤 슬랩의 일부를 예산으로 다시 잘라 그 태스크에게 +/// 넘깁니다. 태스크는 예산만큼만 쓸 수 있어야 하고, 그동안 슬랩의 나머지는 +/// 그대로여야 합니다. 슬랩을 회수하면 태스크와 예산이 한 번에 사라지고 같은 +/// 자리에 같은 것을 다시 만들 수 있어야 하므로 이 순서를 두 번 돕니다. +/// +/// 스택 자리 번호와 슬롯 할당 위치는 들어올 때의 값으로 되돌려 놓습니다. 이 +/// 뒤의 검증들이 남은 스택 자리를 전부 씁니다. +/// +/// # Arguments +/// `iso` - 태스크가 쓸 프레임 크기와 pulse 자리를 가진 환경 +/// `q` - 태스크가 보고에 쓰는 엔드포인트 +fn test_split(iso: &Iso, q: i64, b: &Boot) { + let first = NEXT_SLOT.load(Ordering::Relaxed); + let stacks = NEXT_STACK.load(Ordering::Relaxed); + let (main, fs) = (b.ut_main, iso.fs); + let va = TEST_VA + 47 * fs; + let slab = alloc_slot(); + let tmp = alloc_slot(); + + // 거부 경로. 그래뉼 수 0은 슬롯보다 먼저 걸림 + check("split zero before slots", untyped_split(0, 0, 0) == err::BAD_SIZE); + check("split zero", untyped_split(main, slab, 0) == err::BAD_SIZE); + check("split null source", untyped_split(0, slab, 1) == err::BAD_SLOT); + check("split far source", untyped_split(u64::MAX, slab, 1) == err::BAD_SLOT); + check("split wrong kind", untyped_split(slot::CONSOLE, slab, 1) == err::NOT_UNTYPED); + check("split empty source", untyped_split(slab, tmp, 1) == err::NOT_UNTYPED); + check("split huge", untyped_split(main, slab, u64::MAX) == err::EXHAUSTED); + check("split wide", untyped_split(main, slab, 1 << 52) == err::EXHAUSTED); + check("split occupied", untyped_split(main, slot::CONSOLE, 1) == err::OCCUPIED); + check("split onto itself", untyped_split(main, main, 1) == err::OCCUPIED); + check("split null dest", untyped_split(main, 0, 1) == err::BAD_SLOT); + check("split far dest", untyped_split(main, u64::MAX, 1) == err::BAD_SLOT); + check("split refusals left no cap", cap_delete(slab as i64) == err::BAD_SLOT); + + check("split slab", untyped_split(main, slab, SLAB_GRANULES) == 0); + // 자식 untyped는 복사할 수도 매핑할 수도 없음 + check( + "split no copy", + cap_copy(slab as i64, slot::CNODE as i64, tmp, rights::ALL, 0) == err::BAD_CAP, + ); + check("split no map", map(slab as i64, va, perm::RW) == err::BAD_CAP); + + let base = NEXT_SLOT.load(Ordering::Relaxed); + let words = (fs / 8) as usize; + for round in 0..2u64 { + // 뼈대: 주소 공간과 테이블 셋, 스택, CNode, TCB가 슬랩의 앞쪽 일곱 + let (aspace, _) = make_aspace(slab, b); + let capped = Iso { + ut: slab, + fs, + aspace, + pulse_view: iso.pulse_view, + }; + let t = capped.build(capped_entry as usize as u64, 0, &[(q, rights::W, 0)]); + // 예산: 슬랩에서 다시 잘라 태스크의 CNode로 옮김. 옮긴 뒤로 루트는 그 + // 케이퍼빌리티를 가리킬 수 없고, 되찾는 길은 슬랩의 회수뿐임 + check("split budget", untyped_split(slab, tmp, BUDGET_GRANULES) == 0); + check("split hand over", cap_move(tmp as i64, t.cnode, 2) == 0); + check("split budget left root", untyped_split(tmp, tmp, 1) == err::NOT_UNTYPED); + check("split start", tcb_resume(t.tcb) == 0); + let r = recv(q, ipc::timeout(4)); + check("split report", r.status == 0 && r.mr[0] == CAPPED_ALL); + check( + "split count", + r.mr[1] == BUDGET_GRANULES && r.mr[2] == BUDGET_GRANULES - 1, + ); + + // 태스크가 예산을 다 써도 슬랩의 나머지는 그대로 남아 있음 + let mut last = 0; + for _ in 0..(SLAB_GRANULES - SKELETON_GRANULES - BUDGET_GRANULES) { + last = retype(slab, obj::FRAME); + check("split parent rest", last > 0); + } + check("split parent exact", retype_at(slab, obj::FRAME, tmp) == err::EXHAUSTED); + check("split parent full", untyped_split(slab, tmp, 1) == err::EXHAUSTED); + check("split dirty map", map(last, va, perm::RW) == 0); + // SAFETY: 방금 RW로 매핑된 전용 프레임이고 쓰는 자리는 그 안임 + unsafe { + (va as *mut u64).write_volatile(0x5B17_0000 + round); + (va as *mut u64).add(words - 1).write_volatile(!round); + } + + // 재시작: 슬랩을 회수하면 태스크, 그 CNode, 주소 공간, 예산과 예산으로 + // 만든 것이 한 번에 사라짐. 이미지 프레임의 사본은 슬랩 밖에 있으므로 + // 따로 지움(매핑 기록이 낡은 채로 남아 있음) + check("split restart", cap_revoke(slab as i64) == 0); + check("split took tcb", tcb_resume(t.tcb) == err::BAD_SLOT); + check("split took cnode", cap_delete(t.cnode) == err::BAD_SLOT); + check("split took aspace", cap_delete(aspace) == err::BAD_SLOT); + check("split took frame", unmap(last) == err::BAD_SLOT); + release_slots(base); + NEXT_STACK.store(stacks, Ordering::Relaxed); + + // 재사용: 슬랩은 처음부터 다시, 정확히 제 그래뉼 수만큼 나오고 전부 + // 지워져 있음. 회수 직후에도 내용이 남아 있던 자리(마지막 단계 테이블, + // 태스크의 스택, TCB, 루트가 쓴 프레임)를 골라 그래뉼 전체를 읽음. + // 프레임을 전부 쥔 채로 만들어야 그래뉼마다 한 번씩 나옴 + for i in 0..SLAB_GRANULES { + let f = retype(slab, obj::FRAME); + check("split reuse", f > 0); + if [3, 4, 6, SLAB_GRANULES - 1].contains(&i) { + check("split reuse map", map(f, va, perm::RO) == 0); + // SAFETY: 방금 이 VA에 프레임 하나를 읽기 전용으로 매핑했음 + let clean = (0..words).all(|w| unsafe { (va as *const u64).add(w).read_volatile() } == 0); + check("split reuse zeroed", clean); + check("split reuse unmap", unmap(f) == 0); + } + } + check("split reuse exact", retype_at(slab, obj::FRAME, tmp) == err::EXHAUSTED); + check("split clear", cap_revoke(slab as i64) == 0); + release_slots(base); + } + + // 자식을 삭제해도 부모는 그 뒤에서 계속 잘라냄 + check("split drop slab", cap_delete(slab as i64) == 0); + let g = retype(main, obj::FRAME); + check("split parent alive", g > 0); + release_slots(first); + check("split left the stacks", NEXT_STACK.load(Ordering::Relaxed) == stacks); + put_str("root: untyped split tests pass\n"); +} + /// 태스크가 놓일 수 있는 상태마다 그 태스크를 삭제해 보는 함수입니다. /// /// 삭제된 TCB를 가리키는 큐 링크나 응답 링크가 남으면 그 뒤의 IPC가 사라진 @@ -2116,6 +2383,8 @@ fn test_teardown(iso: &Iso, q: i64) { ); check("revoke stopped cnode", cap_revoke(cn) == 0); check("stopped tcb torn down", tcb_resume(stopped) == err::BAD_STATE); + // 한 번도 실행되지 않은 채 종료된 태스크도 끝난 것으로 보임 + check("stopped tcb ended", tcb_state(stopped) == tcb_status::ENDED); check("delete stopped tcb", cap_delete(stopped) == 0); check("stopped tcb gone", tcb_resume(stopped) == err::BAD_SLOT); check("delete its cnode", cap_delete(cn) == 0); diff --git a/userspace/root-task/src/oracle.rs b/userspace/root-task/src/oracle.rs index 4c98413..6e1cffd 100644 --- a/userspace/root-task/src/oracle.rs +++ b/userspace/root-task/src/oracle.rs @@ -79,8 +79,13 @@ const MODE_AFTER_ZEROIZE: u64 = 4; /// 어느 프레임을 읽고 쓸지는 프로토콜의 계획 함수가 배지와 연산만 보고 /// 정합니다. 본문이 없는 연산이나 요청 프레임이 없는 호출자(운영자)의 요청은 /// 길이를 무엇이라 말하든 어떤 프레임도 읽지 않습니다. -pub(super) extern "C" fn vault_entry(_arg: u64) -> ! { - let mut vault = Vault::new(); +/// +/// # Arguments +/// `again` - 0이면 처음 상태의 볼트로 시작함. 그 밖의 값이면 감독자가 끝난 +/// 볼트의 자리에 다시 띄운 볼트이고, 시드도 키도 받지 않는 지워진 +/// 상태로 시작함(값이 어긋나도 안전한 쪽으로 감) +pub(super) extern "C" fn vault_entry(again: u64) -> ! { + let mut vault = if again == 0 { Vault::new() } else { Vault::retired() }; let mut body = [0u8; MAX_MESSAGE]; let mut out = [0u8; MAX_RESPONSE]; let mut r = recv(1, 0); @@ -410,6 +415,7 @@ pub fn test_oracle(b: &Boot, info: u64) { } check("violator stayed silent", recv(report, ipc::NONBLOCK).status == err::WOULD_BLOCK); check("violator is dead", tcb_resume(tcb) == err::BAD_STATE); + check("violator ended", super::tcb_state(tcb) == super::tcb_status::ENDED); check("oracle client delete", cap_delete(tcb) == 0); }; reports(MODE_SIGNER, proto::signer_badge(1)); diff --git a/userspace/root-task/src/service.rs b/userspace/root-task/src/service.rs index b6c5775..03cdcce 100644 --- a/userspace/root-task/src/service.rs +++ b/userspace/root-task/src/service.rs @@ -13,20 +13,44 @@ //! 프레임은 터미널에 읽기 전용으로 매핑됩니다. 직렬 선에는 인증이 없으므로, //! 선에 닿는 사람은 누구나 이 운영자 권한을 갖습니다(그 이상은 갖지 못함). //! -//! 진짜 터미널을 띄우기 전에, 터미널과 똑같이 배선한 적대적 태스크를 먼저 -//! 돌립니다. 그 태스크는 볼트에 온갖 요청을 보내고, 출력 필터를 두드리고, -//! 읽기 전용 프레임에 쓰고, 루트의 데이터를 읽으려 합니다. 터미널이 장악돼도 -//! 운영자 권한 밖으로 나가지 못한다는 것을 배선 그대로 확인하는 검증입니다. +//! 서비스마다 자리가 하나씩 있습니다. 자리는 untyped에서 잘라낸 슬랩 하나와 +//! 루트 CNode의 슬롯 구간 하나이고, 서비스의 주소 공간과 스택, CNode, TCB는 +//! 전부 그 슬랩에서 나옵니다. 슬랩을 회수하면 서비스가 통째로 사라지고 같은 +//! 자리에 다시 만들 수 있습니다. 서비스에는 untyped를 주지 않습니다. 볼트의 +//! 엔드포인트와 두 서비스가 함께 보는 프레임은 슬랩 밖에 두어, 한 서비스를 +//! 다시 만들어도 다른 서비스의 주소 공간이 바뀌지 않게 합니다. //! -//! 서비스가 시작되면 루트 태스크는 아무도 쥐지 않은 엔드포인트에서 영원히 -//! 기다립니다. 터미널이나 볼트가 죽어도 다시 띄우지 않습니다. +//! 진짜 터미널을 띄우기 전에, 터미널과 똑같이 배선한 적대적 태스크 둘을 +//! 터미널의 자리에서 먼저 돌립니다. 그 태스크는 볼트에 온갖 요청을 보내고, +//! 출력 필터를 두드리고, 읽기 전용 프레임에 쓰고, 루트의 데이터를 읽으려 +//! 합니다. 터미널이 장악돼도 운영자 권한 밖으로 나가지 못한다는 것을 같은 +//! 빌더와 같은 케이퍼빌리티 목록으로 확인하는 검증입니다. 두 태스크는 폴트로 +//! 끝나고, 그때마다 감독자가 자리를 회수하고 다음 것을 만듭니다. 그래서 다시 +//! 띄우는 경로가 부팅할 때마다 실제 배선으로 돕니다. 세 번째로 시작하는 것이 +//! 진짜 터미널입니다. +//! +//! 서비스가 시작되면 루트 태스크는 자기만 쥔 엔드포인트에서 기한을 걸고 +//! 기다리다가, 기한이 될 때마다 두 서비스의 태스크가 끝났는지 커널에 묻습니다 +//! (`k0-sup`의 정책). 끝난 서비스는 회수하고 한도 안에서 다시 띄웁니다. 끝난 +//! 볼트의 슬랩은 다른 것을 만들기 전에 전부 지우고, 다시 띄운 볼트는 시드도 +//! 키도 받지 않습니다. 부트 시드는 첫 볼트에게 한 번 넘긴 뒤로 루트에 남아 +//! 있지 않습니다. 루트 태스크는 서비스가 쥔 것에서는 기다리지 않습니다. 루트 +//! 태스크 자신을 지켜보는 것은 없습니다. +//! +//! 서비스를 시작한 뒤에 감독의 한 단계가 실패하면 루트 태스크는 볼트의 슬랩을 +//! 지우기를 시도한 뒤 끝납니다. 감독자 없이 키가 메모리에 남지 않게 하려는 +//! 것입니다. + +use core::sync::atomic::Ordering; use k0_abi::console::{FLUSH, NONBLOCK}; +use k0_sup::{Host, Id, Limits, Line, State, Supervisor, Why, LIMITS}; use k0_term::Term; use super::{ - cap_copy, cap_delete, check, console_read, err, make_aspace, map_into, obj, perm, put_str, putc, recv, - retype, rights, slot, sys1, syscall, tcb_configure, tcb_resume, yield_now, Boot, + alloc_slot, cap_copy, cap_delete, cap_revoke, check, console_read, err, ipc, make_aspace, map_into, obj, + perm, put_str, putc, recv, retype, rights, slot, sys1, syscall, tcb_configure, tcb_resume, tcb_state, + tcb_status, untyped_split, yield_now, Boot, NEXT_SLOT, }; /// 서비스 태스크의 스택(각자의 주소 공간에서 같은 VA) @@ -34,6 +58,16 @@ const STACK_BASE: u64 = 0x52_0000; const STACK_SIZE: u64 = 0x8000; /// 터미널 CNode에서 Console이 드는 슬롯 const CON: u64 = 1; +/// 서비스 하나의 슬랩(그래뉼 수). 주소 공간과 테이블 셋, 스택, CNode, TCB가 +/// 여기서 나옴(4 KiB 그래뉼에서 14, 16 KiB에서 8) +const SLAB_GRANULES: u64 = 16; +/// 부팅 자가 시험이 쓰는 한도: 기다림 없이 한 번만 다시 띄움 +const TEST_LIMITS: Limits = Limits { + backoff: &[0], + period: LIMITS.period, +}; +/// 태스크가 끝나기를 기다리며 양보하는 횟수의 상한 +const END_YIELDS: u64 = 200_000; fn say(text: &str) { for b in text.bytes() { @@ -270,11 +304,12 @@ fn make_space(ut: u64, b: &Boot) -> i64 { aspace } -/// 태스크 하나를 만들어 실행 대기 상태로 만드는 함수입니다. TCB 슬롯을 줍니다. +/// 태스크 하나를 만들어 구성까지만 해 두는 함수입니다. (TCB 슬롯, CNode 슬롯)을 +/// 줍니다. 재개는 부른 쪽이 빌드의 마지막 단계로 합니다. /// /// # Arguments /// `caps` - 태스크의 CNode 1번 슬롯부터 차례로 넣을 (원본, 남길 권한, 배지) -fn spawn(ut: u64, aspace: i64, entry: u64, arg: u64, caps: &[(i64, u64, u64)]) -> i64 { +fn task(ut: u64, aspace: i64, entry: u64, arg: u64, caps: &[(i64, u64, u64)]) -> (i64, i64) { let cnode = retype(ut, obj::CNODE); check("service cnode", cnode > 0); for (i, &(src, mask, badge)) in caps.iter().enumerate() { @@ -283,63 +318,530 @@ fn spawn(ut: u64, aspace: i64, entry: u64, arg: u64, caps: &[(i64, u64, u64)]) - let tcb = retype(ut, obj::TCB); check( "service task", - tcb > 0 - && tcb_configure(tcb, entry, STACK_BASE + STACK_SIZE, aspace, cnode, arg) == 0 - && tcb_resume(tcb) == 0, + tcb > 0 && tcb_configure(tcb, entry, STACK_BASE + STACK_SIZE, aspace, cnode, arg) == 0, ); - tcb + (tcb, cnode) } -/// 서비스의 볼트를 띄우고 부트 시드를 넘기는 함수입니다. (엔드포인트, 관리자 -/// 케이퍼빌리티, 시드를 넘긴 뒤의 볼트 상태 워드)를 줍니다. +/// 서비스 하나의 자리를 담는 구조체입니다. /// -/// 진짜 부트 시드가 쓰이는 곳은 여기 한 번뿐입니다. 넘긴 뒤에는 루트 쪽의 -/// 사본과 관리자 요청 프레임을 지웁니다. +/// 슬랩은 루트의 CNode에 남아 있고 옮기지 않습니다. 슬롯 구간은 첫 빌드가 +/// 정하고, 그 뒤의 빌드는 같은 슬롯을 다시 씁니다. 그래서 몇 번을 다시 만들어도 +/// 슬롯도 메모리도 더 들지 않습니다. +#[derive(Clone, Copy)] +struct Seat { + /// 이 서비스의 것이 전부 나오는 untyped + slab: u64, + /// 빌드가 쓰는 루트 CNode 슬롯 구간(길이가 0이면 아직 만든 적 없음) + first: u64, + len: u64, + /// 지금 있는 태스크의 TCB와 CNode(없으면 0) + tcb: i64, + cnode: i64, +} + +impl Seat { + /// untyped에서 슬랩을 잘라 빈 자리를 만드는 함수입니다. + fn new(ut: u64) -> Self { + let slab = alloc_slot(); + check("service slab", untyped_split(ut, slab, SLAB_GRANULES) == 0); + Seat { + slab, + first: 0, + len: 0, + tcb: 0, + cnode: 0, + } + } + + /// 자리의 슬롯 구간 안에서 빌더를 돌리는 함수입니다. + /// + /// 첫 빌드는 지금의 할당 위치에서 시작해 쓴 만큼을 구간으로 정합니다. 그 + /// 뒤의 빌드는 할당 위치를 구간의 처음으로 돌려놓고 돌린 뒤, 정확히 구간의 + /// 끝에서 멈췄는지 확인하고 할당 위치를 되돌립니다. 서비스 모드의 루트 + /// 태스크는 한 줄기로만 돌므로 할당 위치를 잠깐 바꿔도 됩니다. + fn within(&mut self, build: impl FnOnce() -> R) -> R { + if self.len == 0 { + self.first = NEXT_SLOT.load(Ordering::Relaxed); + let r = build(); + self.len = NEXT_SLOT.load(Ordering::Relaxed) - self.first; + return r; + } + let saved = NEXT_SLOT.swap(self.first, Ordering::Relaxed); + let r = build(); + check( + "service slot range", + NEXT_SLOT.swap(saved, Ordering::Relaxed) == self.first + self.len, + ); + r + } + + /// 만들어 둔 태스크를 시작하는 함수입니다. 빌드의 마지막 단계입니다. + fn begin(&mut self, (tcb, cnode): (i64, i64)) { + check("service not started", tcb_state(tcb) == tcb_status::NOT_STARTED); + check("service resume", tcb_resume(tcb) == 0); + check("service alive", tcb_state(tcb) == tcb_status::ALIVE); + (self.tcb, self.cnode) = (tcb, cnode); + } +} + +/// 슬랩 밖에 두는 볼트 쪽 오브젝트들을 담는 구조체입니다. #[cfg(feature = "vault")] -fn start_vault(ut: u64, b: &Boot, term_space: i64) -> (i64, i64, u64) { - use k0_vault::proto::{self, alg, request, status}; - use k0_vault::server::wipe; +#[derive(Clone, Copy)] +struct Shared { + /// 볼트 엔드포인트. 볼트를 다시 만들어도 터미널이 쥔 송신 케이퍼빌리티가 + /// 그대로 유효함 + ep: i64, + /// 운영자 응답 프레임(볼트에 쓰기 가능)과 그 읽기 전용 사본(터미널에) + resp: i64, + resp_view: i64, + /// 관리자 요청 프레임의 읽기 전용 사본(볼트에). 원본은 루트에 매핑돼 있음 + req_view: i64, + /// 소거에 쓰는 슬롯 구간의 처음. 슬랩의 그래뉼마다 하나와, 다 나왔는지 + /// 확인하는 빈 자리 하나 + scrub: u64, +} - use super::{call, copy_here, ipc, oracle, take_boot_seed, TEST_VA}; +#[cfg(feature = "vault")] +mod place { + use super::super::TEST_VA; /// 루트가 서비스 볼트의 관리자 요청 프레임을 보는 VA. 루트의 시험용 VA /// 구역(페이지 테이블이 이미 깔린 2MiB) 안에서 다른 검증이 쓰지 않는 자리 - const ROOT_REQ: u64 = TEST_VA + 0x78 * 0x4000; - - let ep = retype(ut, obj::ENDPOINT); - check("service endpoint", ep > 0); - let vault_space = make_space(ut, b); - oracle::link(ut, (0, ROOT_REQ), (vault_space, oracle::VAULT_REQ)); - oracle::link( - ut, - (vault_space, oracle::VAULT_RESP + proto::OPERATOR_FRAME * oracle::FRAME_STEP), - (term_space, port::RESP), - ); - spawn(ut, vault_space, oracle::vault_entry as usize as u64, 0, &[(ep, rights::R, 0)]); - let admin = copy_here(ep, rights::W, proto::ADMIN_BADGE); - check("service admin cap", admin > 0); - - let (mut seed, info) = take_boot_seed(); - for (i, byte) in seed.iter().chain(&info.to_le_bytes()).enumerate() { - // SAFETY: 방금 이 VA에 관리자 요청 프레임을 쓰기 가능으로 매핑했음 - unsafe { (ROOT_REQ as *mut u8).add(i).write_volatile(*byte) }; - } - wipe(&mut seed); - let r = call(admin, ipc::timeout(5), [request::word(request::INIT, alg::NONE), proto::INIT_LEN as u64, 1, 0]); - for i in 0..proto::INIT_LEN { - // SAFETY: 위와 같음 - unsafe { (ROOT_REQ as *mut u8).add(i).write_volatile(0) }; - } - check("service seed delivered", r.status == 0 && r.mr[3] == 1); - put_str(match r.mr[0] { - status::OK => "root: vault seeded\n", - status::NO_ENTROPY => "root: vault has no seed (boot seed has no entropy)\n", - status::UNSUPPORTED => "root: vault has no seed (no algorithm in this image)\n", - _ => super::fail("service seed"), + pub const ROOT_REQ: u64 = TEST_VA + 0x78 * 0x4000; + /// 루트가 운영자 응답 프레임을 지울 때 잠깐 보는 VA + pub const ROOT_RESP: u64 = TEST_VA + 0x79 * 0x4000; +} + +/// 실패로 끝나기 직전에 지울 볼트 슬랩과 소거용 슬롯 구간(0이면 지울 것 없음) +#[cfg(feature = "vault")] +static LAST_SLAB: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0); +#[cfg(feature = "vault")] +static LAST_SCRUB: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0); + +/// 루트 태스크가 실패로 끝나기 직전에 볼트의 메모리를 지우기를 시도하는 +/// 함수입니다. +/// +/// 서비스의 볼트가 시드를 받기 직전부터 켜집니다. 볼트 슬랩을 회수해 볼트를 +/// 끝내고 슬랩의 그래뉼을 전부 프레임으로 다시 만들어 지웁니다. 실패 경로 +/// 안이므로 여기서는 `check`를 쓰지 않고 결과만 한 줄로 남깁니다. 소거용 슬롯에 +/// 무엇이 남아 있었더라도 그것은 이 슬랩에서 나온 것이라 첫 회수가 비웁니다. +#[cfg(feature = "vault")] +pub(super) fn scrub_on_failure() { + use super::retype_at; + + let slab = LAST_SLAB.swap(0, Ordering::Relaxed); + if slab == 0 { + return; + } + let first = LAST_SCRUB.load(Ordering::Relaxed); + let mut done = cap_revoke(slab as i64) == 0; + for i in 0..SLAB_GRANULES { + done &= retype_at(slab, obj::FRAME, first + i) == 0; + } + done &= retype_at(slab, obj::FRAME, first + SLAB_GRANULES) == err::EXHAUSTED; + done &= cap_revoke(slab as i64) == 0; + put_str(if done { + "root: vault erased before exit\n" + } else { + "root: vault not erased\n" }); - let r = call(admin, ipc::timeout(5), [request::word(request::STATUS, alg::NONE), 0, 2, 0]); - check("service vault status", r.status == 0 && r.mr[0] == status::OK && r.mr[3] == 2); - (ep, admin, r.mr[1]) +} + +/// 서비스의 자리들과, 감독자가 시키는 일을 시스템 콜로 하는 구조체입니다. +struct Sys<'a> { + b: &'a Boot, + term: Seat, + /// 터미널의 자리에서 지금까지 시작한 횟수. 처음 둘은 적대적 태스크 + starts: u64, + #[cfg(feature = "vault")] + vault: Seat, + #[cfg(feature = "vault")] + shared: Shared, + /// 감독자의 줄을 내지 않음(부팅 자가 시험) + quiet: bool, +} + +impl<'a> Sys<'a> { + /// 슬랩과 슬랩 밖의 오브젝트를 만드는 함수입니다. + fn new(ut: u64, b: &'a Boot) -> Self { + #[cfg(feature = "vault")] + let shared = { + use super::{copy_here, map}; + + let ep = retype(ut, obj::ENDPOINT); + let resp = retype(ut, obj::FRAME); + let req = retype(ut, obj::FRAME); + check("service shared objects", ep > 0 && resp > 0 && req > 0); + let resp_view = copy_here(resp, rights::R, 0); + let req_view = copy_here(req, rights::R, 0); + check("service read only copies", resp_view > 0 && req_view > 0); + check("service admin frame", map(req, place::ROOT_REQ, perm::RW) == 0); + let scrub = alloc_slot(); + for i in 1..=SLAB_GRANULES { + check("service scrub slots", alloc_slot() == scrub + i); + } + Shared { + ep, + resp, + resp_view, + req_view, + scrub, + } + }; + Sys { + b, + term: Seat::new(ut), + starts: 0, + #[cfg(feature = "vault")] + vault: Seat::new(ut), + #[cfg(feature = "vault")] + shared, + quiet: false, + } + } + + fn seat(&mut self, id: Id) -> &mut Seat { + match id { + Id::Terminal => &mut self.term, + #[cfg(feature = "vault")] + Id::Vault => &mut self.vault, + #[cfg(not(feature = "vault"))] + Id::Vault => super::fail("service without a vault"), + } + } + + /// 터미널의 자리에 태스크를 만들어 시작하는 함수입니다. + /// + /// 처음 두 번은 적대적 태스크이고 그 뒤로는 터미널입니다. 어느 것이든 같은 + /// 빌더와 같은 케이퍼빌리티 목록으로 만듭니다. Console의 입출력 복사본과, + /// 볼트가 있으면 그 엔드포인트의 송신 전용 복사본(운영자 배지)과 응답 + /// 프레임의 읽기 전용 매핑입니다. + fn build_terminal(&mut self) { + let (entry, arg) = match self.starts { + 0 => (hostile_entry as usize as u64, 0), + 1 => (hostile_entry as usize as u64, 1), + _ => (term_entry as usize as u64, 0), + }; + self.starts += 1; + let (b, slab) = (self.b, self.term.slab); + #[cfg(feature = "vault")] + let shared = self.shared; + let made = self.term.within(|| { + let space = make_space(slab, b); + let con = (slot::CONSOLE as i64, rights::R | rights::W, 0); + #[cfg(feature = "vault")] + { + // 응답 프레임의 사본으로는 쓰기 가능한 매핑을 만들 수 없어야 함 + check( + "terminal view is read only", + map_into(shared.resp_view, port::RESP, perm::RW, space) == err::NO_RIGHTS, + ); + check("terminal view", map_into(shared.resp_view, port::RESP, perm::RO, space) == 0); + task(slab, space, entry, arg, &[con, (shared.ep, rights::W, k0_vault::proto::OPERATOR_BADGE)]) + } + #[cfg(not(feature = "vault"))] + task(slab, space, entry, arg, &[con]) + }); + self.term.begin(made); + } + + /// 볼트의 자리에 볼트를 만들어 시작하는 함수입니다. + /// + /// # Arguments + /// `again` - 0이면 처음 상태의 볼트, 그 밖의 값이면 다시 시작된 볼트(시드도 + /// 키도 받지 않음) + #[cfg(feature = "vault")] + fn build_vault(&mut self, again: u64) { + use k0_vault::proto; + + use super::oracle; + + let (b, slab, shared) = (self.b, self.vault.slab, self.shared); + let made = self.vault.within(|| { + let space = make_space(slab, b); + // 관리자 요청 프레임은 볼트에 읽기 전용으로, 운영자 응답 프레임은 + // 쓰기 가능으로 보임 + check( + "vault view is read only", + map_into(shared.req_view, oracle::VAULT_REQ, perm::RW, space) == err::NO_RIGHTS, + ); + check("vault view", map_into(shared.req_view, oracle::VAULT_REQ, perm::RO, space) == 0); + let resp = oracle::VAULT_RESP + proto::OPERATOR_FRAME * oracle::FRAME_STEP; + check("vault response frame", map_into(shared.resp, resp, perm::RW, space) == 0); + task(slab, space, oracle::vault_entry as usize as u64, again, &[(shared.ep, rights::R, 0)]) + }); + self.vault.begin(made); + } + + /// 서비스 하나의 것을 전부 회수하는 함수입니다. + /// + /// 슬랩을 회수하면 태스크, CNode, 주소 공간, 테이블, 스택이 한 번에 + /// 사라집니다. 볼트의 슬랩은 그 자리에서 곧바로 지웁니다. 그다음 구간의 + /// 슬롯을 비우고(이미지 프레임의 사본들이 낡은 매핑 기록을 단 채 남아 + /// 있음), 슬랩 밖의 케이퍼빌리티에 남은 낡은 매핑 기록을 걷어 냅니다. + fn retire_seat(&mut self, id: Id) { + let seat = *self.seat(id); + check("retire a built seat", seat.len != 0 && seat.tcb != 0); + check("retire revoke", cap_revoke(seat.slab as i64) == 0); + check("retire took the task", tcb_state(seat.tcb) == err::BAD_SLOT); + #[cfg(feature = "vault")] + if id == Id::Vault { + self.scrub(); + } + for s in seat.first..seat.first + seat.len { + let r = cap_delete(s as i64); + check("retire slot", r == 0 || r == err::BAD_SLOT); + } + #[cfg(feature = "vault")] + match id { + Id::Terminal => check("retire terminal view", super::unmap(self.shared.resp_view) == 0), + Id::Vault => { + check("retire vault view", super::unmap(self.shared.req_view) == 0); + check("retire vault response", super::unmap(self.shared.resp) == 0); + self.clear_response(); + } + } + let seat = self.seat(id); + (seat.tcb, seat.cnode) = (0, 0); + } + + /// 방금 회수한 볼트 슬랩을 전부 지우는 함수입니다. + /// + /// 회수는 메모리를 지우지 않고, 지우는 것은 재분류입니다. 슬랩의 그래뉼을 + /// 전부 프레임으로 다시 만들어 지우는데, 프레임을 전부 쥔 채로 만들어야 + /// 그래뉼마다 한 번씩 나옵니다(하나씩 만들고 지우면 첫 그래뉼만 거듭 + /// 나옴). 정확히 슬랩의 그래뉼 수만큼 나오고 끝났는지를 확인합니다. + #[cfg(feature = "vault")] + fn scrub(&mut self) { + use super::retype_at; + + let (slab, first) = (self.vault.slab, self.shared.scrub); + for i in 0..SLAB_GRANULES { + check("scrub frame", retype_at(slab, obj::FRAME, first + i) == 0); + } + check( + "scrub covered the slab", + retype_at(slab, obj::FRAME, first + SLAB_GRANULES) == err::EXHAUSTED, + ); + check("scrub release", cap_revoke(slab as i64) == 0); + } + + /// 운영자 응답 프레임을 지우는 함수입니다. 슬랩 밖에 있어서 소거가 닿지 + /// 않고, 끝난 볼트가 마지막으로 쓴 공개키가 남아 있을 수 있습니다. + #[cfg(feature = "vault")] + fn clear_response(&mut self) { + use super::{map, unmap}; + + check("clear response map", map(self.shared.resp, place::ROOT_RESP, perm::RW) == 0); + for i in 0..(self.b.frame_size / 8) as usize { + // SAFETY: 방금 이 VA에 응답 프레임 하나를 쓰기 가능으로 매핑했고 + // 쓰는 자리는 그 프레임 안임 + unsafe { (place::ROOT_RESP as *mut u64).add(i).write_volatile(0) }; + } + check("clear response unmap", unmap(self.shared.resp) == 0); + } + + /// 자리의 태스크가 끝날 때까지 양보하며 기다리는 함수입니다. 정해진 횟수 + /// 안에 끝나지 않으면 `false` + fn ends(&mut self, id: Id) -> bool { + let tcb = self.seat(id).tcb; + for _ in 0..END_YIELDS { + match tcb_state(tcb) { + tcb_status::ENDED => return true, + tcb_status::ALIVE => yield_now(), + _ => return false, + } + } + false + } + + /// 볼트를 다시 띄우는 경로를 검증하는 함수입니다. + /// + /// 시드를 받지 않은 볼트를 볼트의 자리에 만들고, 그 CNode를 회수해 볼트를 + /// 끝낸 뒤, 서비스의 폴 루프가 쓰는 바로 그 함수로 회수와 소거와 다시 + /// 만들기를 돌립니다. 다시 뜬 볼트는 지워진 상태여야 하고 시드를 받지 + /// 않아야 합니다. 끝나면 자리를 비워, 서비스의 볼트가 같은 자리에서 + /// 처음부터 만들어지게 합니다. 이 검증의 볼트는 비밀을 쥔 적이 없습니다. + #[cfg(feature = "vault")] + fn test_vault_restart(&mut self) { + use k0_vault::proto::{self, alg, request, state, status, status_word}; + + use super::{call, copy_here}; + + self.quiet = true; + self.build_vault(0); + let admin = copy_here(self.shared.ep, rights::W, proto::ADMIN_BADGE); + check("restart test admin cap", admin > 0); + let ask = |op: u64, len: u64, nonce: u64| { + let r = call(admin, ipc::timeout(5), [request::word(op, alg::NONE), len, nonce, 0]); + check("restart test answer", r.status == 0 && r.mr[3] == nonce); + r.mr + }; + let mr = ask(request::STATUS, 0, 1); + check( + "restart test fresh vault", + mr[0] == status::OK && status_word::state(mr[1]) == state::FRESH, + ); + + // 볼트의 CNode에서 나온 것을 회수하면 볼트에 묶인 복사본이 사라져 + // 볼트가 종료됨. 수신을 기다리던 태스크라 커널 줄은 나오지 않음 + let old = self.vault.tcb; + check("restart test end the vault", cap_revoke(self.vault.cnode) == 0); + check("restart test vault ended", tcb_state(old) == tcb_status::ENDED); + let nobody = call(admin, ipc::NONBLOCK, [request::word(request::STATUS, alg::NONE), 0, 9, 0]); + check("restart test no receiver", nobody.status == err::WOULD_BLOCK); + + let mut sup = Supervisor::new(TEST_LIMITS, true); + check("restart test poll", sup.poll(self)); + check( + "restart test vault is back", + sup.state(Id::Vault) == State::Up && sup.restarts(Id::Vault) == 1 && sup.state(Id::Terminal) == State::Up, + ); + // 다시 만든 볼트는 같은 슬롯에 놓인 새 태스크임(자리를 다시 씀) + check( + "restart test seat reused", + self.vault.tcb == old && tcb_state(old) == tcb_status::ALIVE, + ); + + // 다시 뜬 볼트는 지워진 상태로 시작하고, 재료가 충분하다고 적힌 시드를 + // 넘겨도 받지 않음. 넘기는 값은 누구나 아는 값임 + let mr = ask(request::STATUS, 0, 2); + check( + "restart test vault is zeroized", + mr[0] == status::OK && status_word::state(mr[1]) == state::ZEROIZED, + ); + for i in 0..proto::INIT_LEN { + let byte = if i < 32 { 0x5A } else { [32u8, 0, 0, 0, 0, 0, 0, 0][i - 32] }; + // SAFETY: 관리자 요청 프레임은 루트에 쓰기 가능으로 매핑돼 있음 + unsafe { (place::ROOT_REQ as *mut u8).add(i).write_volatile(byte) }; + } + let mr = ask(request::INIT, proto::INIT_LEN as u64, 3); + for i in 0..proto::INIT_LEN { + // SAFETY: 위와 같음 + unsafe { (place::ROOT_REQ as *mut u8).add(i).write_volatile(0) }; + } + check("restart test seed refused", mr[0] == status::DENIED); + let mr = ask(request::STATUS, 0, 4); + check("restart test still zeroized", status_word::state(mr[1]) == state::ZEROIZED); + + self.retire_seat(Id::Vault); + check("restart test drop admin", cap_delete(admin) == 0); + self.quiet = false; + put_str("root: vault restart test pass\n"); + } + + /// 서비스의 볼트를 만들고 부트 시드를 넘기는 함수입니다. (관리자 + /// 케이퍼빌리티, 시드를 넘긴 뒤의 볼트 상태 워드)를 줍니다. + /// + /// 진짜 부트 시드가 쓰이는 곳은 여기 한 번뿐입니다. 넘긴 뒤에는 루트 쪽의 + /// 사본과 관리자 요청 프레임을 지웁니다. 나중에 다시 띄우는 볼트는 이 + /// 함수를 거치지 않습니다. + #[cfg(feature = "vault")] + fn seed_vault(&mut self) -> (i64, u64) { + use k0_vault::proto::{self, alg, request, status}; + use k0_vault::server::wipe; + + use super::{call, copy_here, take_boot_seed}; + + self.build_vault(0); + let admin = copy_here(self.shared.ep, rights::W, proto::ADMIN_BADGE); + check("service admin cap", admin > 0); + // 여기서부터 이 볼트는 비밀을 쥠. 루트가 실패로 끝나면 지우게 해 둠 + LAST_SCRUB.store(self.shared.scrub, Ordering::Relaxed); + LAST_SLAB.store(self.vault.slab, Ordering::Relaxed); + + let (mut seed, info) = take_boot_seed(); + for (i, byte) in seed.iter().chain(&info.to_le_bytes()).enumerate() { + // SAFETY: 관리자 요청 프레임은 루트에 쓰기 가능으로 매핑돼 있음 + unsafe { (place::ROOT_REQ as *mut u8).add(i).write_volatile(*byte) }; + } + wipe(&mut seed); + let r = call(admin, ipc::timeout(5), [request::word(request::INIT, alg::NONE), proto::INIT_LEN as u64, 1, 0]); + for i in 0..proto::INIT_LEN { + // SAFETY: 위와 같음 + unsafe { (place::ROOT_REQ as *mut u8).add(i).write_volatile(0) }; + } + check("service seed delivered", r.status == 0 && r.mr[3] == 1); + put_str(match r.mr[0] { + status::OK => "root: vault seeded\n", + status::NO_ENTROPY => "root: vault has no seed (boot seed has no entropy)\n", + status::UNSUPPORTED => "root: vault has no seed (no algorithm in this image)\n", + _ => super::fail("service seed"), + }); + let r = call(admin, ipc::timeout(5), [request::word(request::STATUS, alg::NONE), 0, 2, 0]); + check("service vault status", r.status == 0 && r.mr[0] == status::OK && r.mr[3] == 2); + (admin, r.mr[1]) + } + + /// 적대적 태스크 둘을 터미널의 자리에서 돌리며 터미널을 다시 띄우는 경로를 + /// 검증하는 함수입니다. + /// + /// 둘 다 폴트로 끝나야 하고(그동안 낸 줄과 폴트 수는 시험 하니스가 확인함), + /// 끝날 때마다 폴 루프가 쓰는 바로 그 함수가 자리를 회수합니다. 첫 번째 + /// 뒤에는 한도 안이라 다음 것을 만들고, 두 번째 뒤에는 한도를 다 써서 + /// 만들지 않습니다. 볼트는 이 감독자에게 맡기지 않습니다(터미널이 + /// 내려갔다고 서비스의 볼트를 지우면 안 됨). 끝나면 자리가 비어 있습니다. + fn test_terminal_restart(&mut self) { + self.quiet = true; + let mut sup = Supervisor::new(TEST_LIMITS, false); + self.build_terminal(); + check("first hostile task ended", self.ends(Id::Terminal)); + check("terminal restart poll", sup.poll(self)); + check( + "second hostile task started", + sup.state(Id::Terminal) == State::Up && sup.restarts(Id::Terminal) == 1 && self.starts == 2, + ); + check("second hostile task ended", self.ends(Id::Terminal)); + check("terminal restart last poll", !sup.poll(self)); + check( + "terminal seat is empty", + sup.state(Id::Terminal) == State::Down(Why::Spent) && self.term.tcb == 0 && self.starts == 2, + ); + self.quiet = false; + put_str("root: terminal restart test pass\n"); + } +} + +impl Host for Sys<'_> { + fn ended(&mut self, id: Id) -> bool { + let tcb = self.seat(id).tcb; + // 아직 한 번도 만들지 않은 자리(부팅 자가 시험에서만 있음) + if tcb == 0 { + return false; + } + match tcb_state(tcb) { + tcb_status::ALIVE => false, + tcb_status::ENDED => true, + _ => super::fail("service task state"), + } + } + + fn input_present(&mut self) -> bool { + // 버리는 플래그 없이 물음. 받아 둔 바이트가 있으면 하나를 가져가지만, + // 새 터미널은 시작하면서 그때까지의 입력을 어차피 버림 + console_read(slot::CONSOLE, NONBLOCK).0 != err::NO_DEVICE + } + + fn retire(&mut self, id: Id) { + self.retire_seat(id); + } + + fn rebuild(&mut self, id: Id) { + match id { + Id::Terminal => self.build_terminal(), + #[cfg(feature = "vault")] + Id::Vault => self.build_vault(1), + #[cfg(not(feature = "vault"))] + Id::Vault => super::fail("service without a vault"), + } + } + + fn line(&mut self, line: Line) { + if !self.quiet { + line.write(put_str); + } + } } /// 서비스를 시작하는 함수입니다. 시작했으면 돌아오지 않습니다. @@ -357,42 +859,42 @@ pub fn start(b: &Boot) { return; } let ut = super::late_untyped(b); - let con = slot::CONSOLE as i64; - let term_space = make_space(ut, b); + let mut sys = Sys::new(ut, b); + // 루트만 쥐는 엔드포인트. 메시지는 오지 않으므로 수신은 기한으로만 끝남 + let wait = retype(ut, obj::ENDPOINT); + check("service wait endpoint", wait > 0); #[cfg(feature = "vault")] - let (ep, admin, before) = start_vault(ut, b, term_space); - #[cfg(feature = "vault")] - let caps = [(con, rights::R | rights::W, 0), (ep, rights::W, k0_vault::proto::OPERATOR_BADGE)]; - #[cfg(not(feature = "vault"))] - let caps = [(con, rights::R | rights::W, 0)]; - - // 터미널과 같은 주소 공간, 같은 케이퍼빌리티 목록으로 적대적 태스크를 돌림. - // 둘 다 폴트로 죽어야 하고, 그동안 낸 줄과 폴트 수는 시험 하니스가 확인함 - for mode in [0, 1] { - let tcb = spawn(ut, term_space, hostile_entry as usize as u64, mode, &caps); - for _ in 0..6000 { - yield_now(); - } - check("hostile task delete", cap_delete(tcb) == 0); - } + let (admin, before) = { + sys.test_vault_restart(); + sys.seed_vault() + }; + sys.test_terminal_restart(); #[cfg(feature = "vault")] { use k0_vault::proto::{alg, request, status}; // 볼트는 살아 있고 상태가 그대로임. 관리자 권한은 여기서 내려놓음 - let r = super::call(admin, super::ipc::timeout(5), [request::word(request::STATUS, alg::NONE), 0, 3, 0]); + let r = super::call(admin, ipc::timeout(5), [request::word(request::STATUS, alg::NONE), 0, 3, 0]); check("vault survived the hostile task", r.status == 0 && r.mr[0] == status::OK && r.mr[1] == before); check("drop admin cap", cap_delete(admin) == 0); } - // 터미널의 시작 줄이 이 줄의 한가운데에 끼어들지 않게 먼저 찍음 + // 터미널의 시작 줄이 이 줄의 한가운데에 끼어들지 않게 먼저 찍음. 터미널을 + // 재개하는 것은 그 뒤의 마지막 단계임 put_str("root: service started\n"); - spawn(ut, term_space, term_entry as usize as u64, 0, &caps); - // 루트의 일은 끝났음. 아무도 쥐지 않은 엔드포인트에서 기다려, 입력이 없는 - // 동안 커널이 다음 인터럽트까지 쉬게 함 - let quiet = retype(ut, obj::ENDPOINT); - check("service idle endpoint", quiet > 0); + sys.build_terminal(); + + // 감독: 기한이 될 때마다 두 서비스가 끝났는지 묻고 정책대로 함. 루트는 + // 서비스가 쥔 것에서는 기다리지 않으므로 서비스가 루트를 붙잡아 둘 수 없음 + let mut sup = Supervisor::new(LIMITS, cfg!(feature = "vault")); + loop { + check("supervisor wait", recv(wait, ipc::timeout(1)).status == err::TIMEOUT); + if !sup.poll(&mut sys) { + break; + } + } + // 감독할 것이 남지 않았음. 기한 없이 기다려 커널이 쉬게 함 loop { - let _ = recv(quiet, 0); + let _ = recv(wait, 0); } }