diff --git a/.dockerignore b/.dockerignore index 2f7896d..4d8ffcf 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1 +1,30 @@ -target/ +# Nothing enters the CI image unless it is listed here. Build output, editor and tool state, +# local notes and logs stay out, whatever they are called. `.git` is kept: the threat model asks +# reporters to quote `git -C /src rev-parse HEAD` from inside the container. +# A new top-level entry that the build or the tests need must be added below. +* +!.cargo +!.git +!.gitattributes +!.gitignore +!.github +!Cargo.lock +!Cargo.toml +!LICENSE +!rust-toolchain.toml +!assets +!ci +!crates +!design +!kernel +!loader +!tools +!userspace +!vendor +!*.md +# Local files that .gitignore also keeps out, at any depth inside the listed directories +**/NO-COMMIT* +**/target +**/.DS_Store +**/*.log +**/*.rs.bk diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 38ff609..bf4bdb7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -91,9 +91,9 @@ $ cargo build -p k0-kernel --features console --offline $ tools/qemu-boot-test.sh # boot under QEMU and check the self-tests ``` -`tools/host-test.sh` runs the tests of `k0-abi`, `k0-cap`, `k0-boot` and `k0-efi` on any host (221 tests on an AArch64 host, 161 elsewhere). 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` and `k0-efi` on any host (250 tests on an AArch64 host, 164 elsewhere). 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`. Set `K0_BOOT_TIMEOUT` (seconds) on slow machines. It reads the serial port, so it needs an image with a console driver. To test an image without console, use `K0_BOOT_MEMLOG`, `K0_BOOT_SERIAL=empty` and `K0_BOOT_CONSOLE_PAGE`, which are described in "Testing an image without console" in [USAGE.md](USAGE.md#testing-an-image-without-console). +`tools/qemu-boot-test.sh` boots the debug kernel, checks the boot log line by line in a fixed order, fails on any error marker, and stops QEMU as soon as the root task reports `root: sched tests pass`. Besides the pass lines, it expects `k0: kernel reserve ` before the `k0: untyped ` lines, `k0: idle (waiting for a timeout)` and `root: timeout tests pass` after `root: teardown tests pass`, and `root: kernel reserve tests pass` after `root: revocation tests pass`. Any line that starts with `k0: all tasks` is a failure. It also counts the timer tick lines between `root: teardown tests pass` and `root: timeout tests pass` and wants at least 4, because EL0 has no clock and this is how the lower bound of a timeout is checked. The timeout tests wait for real ticks, so a boot takes about 4 seconds longer than it did before. 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). 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: @@ -159,7 +159,16 @@ $ docker run --rm --network none k0-ci tools/host-test.sh $ docker run --rm --network none k0-ci tools/boot-matrix.sh ``` -Run this from **a clean checkout**, because the build context includes everything in the working directory. +Run this from **a clean checkout**, because the build context is the working directory. The following list describes how the image is made. + +- **Base image**: it is pinned by the digest of its multi-architecture index (`debian:bookworm@sha256:...`). +- **Rust toolchain**: the image does not use rustup. `ci/install-toolchain.py` pins the SHA-256 of the Rust 1.89.0 channel manifest and checks every package it installs (rustc, cargo, rust-std for the host and for `aarch64-unknown-none-softfloat` and `aarch64-unknown-uefi`, rust-src and llvm-tools) against the hashes in that manifest. A mismatch fails the image build. +- **Build context**: `.dockerignore` is an allowlist, so nothing enters the image unless it is listed there. **A new top-level file or directory** that the build or the tests need must be added to it. `.git` is kept in the image. + +> [!NOTE] +> Not everything is pinned. The versions of the Debian packages float (apt checks them with the archive keys inside the pinned base image), and so do the GitHub runner images. The GitHub Actions used by the workflows are pinned by commit hash. + +Developers still use rustup on their own machines. Only the CI image changed. ## Rules for kernel changes diff --git a/CONTRIBUTING_KR.md b/CONTRIBUTING_KR.md index e23fd76..6c8da7f 100644 --- a/CONTRIBUTING_KR.md +++ b/CONTRIBUTING_KR.md @@ -93,9 +93,9 @@ $ cargo build -p k0-kernel --features console --offline $ tools/qemu-boot-test.sh # QEMU 부팅과 자가 테스트 확인 ``` -`tools/host-test.sh`는 `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`의 테스트를 어느 호스트에서나 실행합니다(AArch64 호스트에서 221개, 그 밖에서 161개). `k0-mm` 테스트는 AArch64 인라인 어셈블리를 포함하기 때문에 AArch64 호스트(Apple Silicon 또는 Linux arm64)에서만 실행되며, 스크립트가 4 KiB와 16 KiB 그래뉼 두 구성으로 모두 돌립니다. +`tools/host-test.sh`는 `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`의 테스트를 어느 호스트에서나 실행합니다(AArch64 호스트에서 250개, 그 밖에서 164개). `k0-mm` 테스트는 AArch64 인라인 어셈블리를 포함하기 때문에 AArch64 호스트(Apple Silicon 또는 Linux arm64)에서만 실행되며, 스크립트가 4 KiB와 16 KiB 그래뉼 두 구성으로 모두 돌립니다. -`tools/qemu-boot-test.sh`는 디버그 커널을 부팅하고 부팅 로그를 정해진 순서대로 한 줄씩 확인합니다. 에러 표식이 하나라도 나오면 실패하고, 루트 태스크가 `root: sched tests pass`를 출력하면 곧바로 QEMU를 종료합니다. 느린 환경에서는 `K0_BOOT_TIMEOUT`(초)을 늘려 주세요. 직렬 포트를 읽기 때문에 콘솔 드라이버가 있는 이미지가 필요합니다. 콘솔 없는 이미지를 시험하려면 [USAGE_KR.md](USAGE_KR.md#콘솔-없는-이미지-시험)의 "콘솔 없는 이미지 시험"에 설명된 `K0_BOOT_MEMLOG`, `K0_BOOT_SERIAL=empty`, `K0_BOOT_CONSOLE_PAGE`를 사용하세요. +`tools/qemu-boot-test.sh`는 디버그 커널을 부팅하고 부팅 로그를 정해진 순서대로 한 줄씩 확인합니다. 에러 표식이 하나라도 나오면 실패하고, 루트 태스크가 `root: sched tests pass`를 출력하면 곧바로 QEMU를 종료합니다. 통과 줄 외에도 `k0: untyped ` 줄보다 앞의 `k0: kernel reserve `, `root: teardown tests pass` 뒤의 `k0: idle (waiting for a timeout)`와 `root: timeout tests pass`, `root: revocation tests pass` 뒤의 `root: kernel reserve tests pass`를 기대합니다. `k0: all tasks`로 시작하는 줄은 모두 실패입니다. `root: teardown tests pass`와 `root: timeout tests pass` 사이의 타이머 틱 줄도 세어 4개 이상을 요구하는데, EL0에는 시계가 없어서 이것이 타임아웃의 하한을 확인하는 방법이기 때문입니다. 타임아웃 테스트는 실제 틱을 기다리므로 부팅 한 번이 이전보다 약 4초 더 걸립니다. 느린 환경에서는 `K0_BOOT_TIMEOUT`(초)을 늘려 주세요. 직렬 포트를 읽기 때문에 콘솔 드라이버가 있는 이미지가 필요합니다. 콘솔 없는 이미지를 시험하려면 [USAGE_KR.md](USAGE_KR.md#콘솔-없는-이미지-시험)의 "콘솔 없는 이미지 시험"에 설명된 `K0_BOOT_MEMLOG`, `K0_BOOT_SERIAL=empty`, `K0_BOOT_CONSOLE_PAGE`를 사용하세요. 기본 QEMU CPU 모델(`cortex-a72`)에는 PAC, PAN, RNDR이 없습니다. 이 경로까지 검증하려면 QEMU의 `max` 모델로 부팅하고 해당 로그 줄을 필수로 지정하세요. 커널 경로 뒤의 인자는 그대로 QEMU에 전달됩니다. 다음과 같이 입력할 수 있습니다. @@ -163,7 +163,16 @@ $ docker run --rm --network none k0-ci tools/host-test.sh $ docker run --rm --network none k0-ci tools/boot-matrix.sh ``` -빌드 컨텍스트에 작업 디렉터리의 모든 파일이 들어가므로 **깨끗한 체크아웃에서 실행**해 주세요. +빌드 컨텍스트는 작업 디렉터리이므로 **깨끗한 체크아웃에서 실행**해 주세요. 이미지는 다음과 같이 만들어집니다. + +- **베이스 이미지**: 멀티 아키텍처 인덱스의 다이제스트(`debian:bookworm@sha256:...`)로 고정되어 있습니다. +- **Rust 툴체인**: 이미지에서는 rustup을 사용하지 않습니다. `ci/install-toolchain.py`가 Rust 1.89.0 채널 매니페스트의 SHA-256을 고정해 두고, 설치하는 모든 패키지(rustc, cargo, 호스트용과 `aarch64-unknown-none-softfloat`·`aarch64-unknown-uefi`용 rust-std, rust-src, llvm-tools)를 그 매니페스트의 해시와 대조합니다. 하나라도 다르면 이미지 빌드가 실패합니다. +- **빌드 컨텍스트**: `.dockerignore`는 허용 목록이므로, 목록에 없는 것은 이미지에 들어가지 않습니다. 빌드나 테스트에 필요한 **새 최상위 파일 또는 디렉터리**는 이 목록에 추가해야 합니다. `.git`은 이미지에 포함됩니다. + +> [!NOTE] +> 모든 것이 고정되어 있지는 않습니다. Debian 패키지의 버전은 고정되지 않았고(apt는 고정된 베이스 이미지 안의 아카이브 키로 검증합니다), GitHub 러너 이미지도 마찬가지입니다. 워크플로가 사용하는 GitHub Actions는 커밋 해시로 고정되어 있습니다. + +개발자는 여전히 자기 컴퓨터에서 rustup을 사용합니다. 바뀐 것은 CI 이미지뿐입니다. ## 커널 변경 규칙 diff --git a/INTRODUCTION.md b/INTRODUCTION.md index e245903..feb6e35 100644 --- a/INTRODUCTION.md +++ b/INTRODUCTION.md @@ -10,7 +10,7 @@ This document explains in plain words what K0 is, what it can do today and what ## What K0 is -An operating system kernel is the program that controls the hardware and decides what every other program may do. Most kernels are large and do many jobs themselves. K0 is a **microkernel**: it does only the few jobs that must be done inside the kernel and leaves everything else to ordinary programs. The kernel side is about 7,400 lines of Rust and assembly (comments included, tests excluded). It is small enough to read from start to end. +An operating system kernel is the program that controls the hardware and decides what every other program may do. Most kernels are large and do many jobs themselves. K0 is a **microkernel**: it does only the few jobs that must be done inside the kernel and leaves everything else to ordinary programs. The kernel side is about 11,800 lines of Rust and assembly (comments included, tests excluded). It is small enough to read from start to end. The most important of those jobs is keeping programs apart. Think of a dormitory. Each room is a block of memory, each key opens one thing, and the kernel is the caretaker. A resident can open only the doors they hold a key for. A copy cannot be turned into a stronger key, and when a key is taken back, every copy made from it stops working too. In K0 these keys are called **capabilities**. The idea comes from the seL4 kernel. @@ -131,6 +131,9 @@ These features only add and are not in `default`, so **every build command must Memory is placed on an address space's map only by showing that address space's key (MAP, UNMAP). Keys carry rights (read, write, execute). A mailbox key can carry a tag that tells the receiver who sent a message (badge). Keys can be copied with the same or fewer rights, or moved between slots (CAP_COPY, CAP_MOVE). - **Running tasks**: a task is tied to one key ring and one address space when it is set up (TCB_CONFIGURE) and then started (TCB_RESUME). Tasks take turns, and a timer interrupts a task that runs too long (round-robin scheduling with timer preemption). A task can give up its turn (YIELD) or finish (EXIT). - **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)`. +- **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. - Every key copied from it is removed as well. @@ -226,13 +229,22 @@ What it stops: - **Access to resources and memory**: a task cannot use a resource it holds no key for, and it cannot see memory that is not on its own map. > [!WARNING] -> Availability is not protected. A task can still bring everything to a halt. +> Availability is not protected in general. A task can still slow down or block the other tasks, as the list below shows. What it does not stop: -- **Availability**: there are two cases. - - If every task ends up waiting for a message, the kernel stops the processor core. A confined task can cause this by being the last one to wait. - - A task given a lot of free memory can use up the kernel's fixed tables (40 page tables for the kernel's own use, 256 address space entries), and then nobody can create new objects. +- **Availability**: three things improved, but a lot is still open. + - The kernel no longer stops when every task is waiting. It idles and keeps handling timer ticks. + - A task can limit its own waits with a timeout. + - The kernel's two tables for page tables and address spaces can no longer be used up by a task. + + Still open: + + - A task that waits without a timeout can wait forever if its partner never acts. Timeouts are used per call, so a server that must stay responsive has to give one on every wait. + - There is no priority and no CPU budget. Tasks take turns in equal slices, and a task that holds a lot of free memory can create many tasks and shrink everyone else's share. + - The kernel cannot be interrupted while it handles a system call. A long call, such as taking back a key to a large block of memory, delays every other task and every timeout. + - A fatal error inside the kernel, or an error from the hardware that the kernel cannot attribute to one task, still stops the whole machine. + - The kernel part of the boot log can be filled up by crash and exit lines. - **Tasks that share a key ring and an address space**: such tasks are not isolated from each other. They behave like threads, parts of one program that share everything. - **Control of a task**: whoever holds the key to a task, to its key ring or to its address space controls that task. @@ -247,7 +259,7 @@ Missing features: - **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. -- **Timeouts and multicore**: there are no timeouts, and only one processor core is used. +- **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. - **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). @@ -269,9 +281,9 @@ Missing features: Missing protection and assurance: -- **Availability guarantees**: see the previous section. +- **Availability guarantees**: see the previous section. Several ways to block other tasks remain. - **DMA isolation**: some devices read and write memory directly, without the processor (DMA). Once devices are handed to programs, a memory map for devices (an IOMMU, such as the SMMU on ARM) has to stop such a device from reading all memory. Nothing for this exists yet. -- **Side channels**: secrets can leak through timing or through caches the processor shares, rather than by direct access. A few such leaks are closed (programs cannot read the hardware counters, and the TLB is emptied whenever the address space changes). There is no general defence against cache or timing side channels, and they have not been analysed. +- **Side channels**: secrets can leak through timing or through caches the processor shares, rather than by direct access. A few such leaks are closed (programs cannot read the hardware counters, and the TLB is emptied whenever the address space changes). Timeouts give programs a clock, but it is as coarse as one timer tick. Whether that can help an attack has not been analysed. There is no general defence against cache or timing side channels, and they have not been analysed. - **Waiting senders**: taking a key back does not cancel a sender already waiting at the mailbox. Its message is still delivered once. - **Basis of assurance**: assurance comes from testing only. - Unit tests and fuzzing (feeding random, broken input to find crashes) on the build machine diff --git a/INTRODUCTION_KR.md b/INTRODUCTION_KR.md index d22f666..5a83295 100644 --- a/INTRODUCTION_KR.md +++ b/INTRODUCTION_KR.md @@ -10,7 +10,7 @@ ## K0는 무엇인가 -운영체제 커널은 하드웨어를 다루고, 다른 모든 프로그램이 무엇을 할 수 있는지 정하는 프로그램입니다. 대부분의 커널은 크고 많은 일을 직접 합니다. K0는 **마이크로커널**이라서 커널 안에서만 할 수 있는 몇 가지 일만 하고, 나머지는 일반 프로그램에 맡깁니다. 커널 쪽 코드는 주석을 포함하고 테스트를 제외하면 Rust와 어셈블리 약 7,400줄입니다. 처음부터 끝까지 읽을 수 있는 크기입니다. +운영체제 커널은 하드웨어를 다루고, 다른 모든 프로그램이 무엇을 할 수 있는지 정하는 프로그램입니다. 대부분의 커널은 크고 많은 일을 직접 합니다. K0는 **마이크로커널**이라서 커널 안에서만 할 수 있는 몇 가지 일만 하고, 나머지는 일반 프로그램에 맡깁니다. 커널 쪽 코드는 주석을 포함하고 테스트를 제외하면 Rust와 어셈블리 약 11,800줄입니다. 처음부터 끝까지 읽을 수 있는 크기입니다. 그 일 가운데 가장 중요한 것은 프로그램끼리 떼어 놓는 것입니다. 기숙사를 떠올려 보세요. 방 하나는 메모리 한 덩어리, 열쇠 하나는 무언가 하나를 여는 도구, 커널은 관리인입니다. 입주자는 열쇠를 가진 문만 열 수 있습니다. 복사한 열쇠를 더 강한 열쇠로 바꿀 수 없고, 열쇠를 회수당하면 거기서 복사한 열쇠도 전부 쓸 수 없게 됩니다. K0에서는 이 열쇠를 **케이퍼빌리티**라고 부릅니다. 이 생각은 seL4 커널에서 왔습니다. @@ -131,6 +131,9 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. 메모리는 그 주소 공간의 열쇠를 보여 줘야만 그 주소 공간의 지도에 올릴 수 있습니다(MAP, UNMAP). 열쇠에는 권한(읽기, 쓰기, 실행)이 있습니다. 우편함 열쇠에는 누가 보냈는지 받는 쪽에 알려 주는 표식(배지)을 붙일 수 있습니다. 열쇠는 권한을 그대로 두거나 줄여서 복사하거나, 다른 슬롯으로 옮길 수 있습니다(CAP_COPY, CAP_MOVE). - **태스크 실행**: 태스크는 준비할 때 열쇠고리 하나와 주소 공간 하나에 묶이고(TCB_CONFIGURE) 그다음 시작됩니다(TCB_RESUME). 태스크는 차례를 돌아가며 실행되고, 너무 오래 도는 태스크는 타이머가 끊습니다(타이머 선점이 있는 라운드 로빈 스케줄링). 태스크는 자기 차례를 양보하거나(YIELD) 끝낼 수 있습니다(EXIT). - **메시지**: 태스크는 프로세서 레지스터에 담긴 짧은 메시지를 주고받습니다. 보내는 쪽은 받는 쪽이 메시지를 가져갈 때까지 기다립니다(동기 IPC: SEND, RECV, CALL, REPLY_RECV). 보내려면 우편함 열쇠에 쓰기 권한이, 받으려면 읽기 권한이 있어야 합니다. 받는 쪽은 보낸 쪽 열쇠의 표식을 알게 되고, 답장할 권리는 한 번만 사용할 수 있습니다. +- **타임아웃**: 이 호출들은 모두 제한 시간을 줄 수 있습니다. 단위는 타이머 틱입니다(1틱은 1초). 제한 시간 안에 상대가 오지 않으면 호출이 오류(`TIMEOUT`, 또는 `CALL`이 전달됐지만 답이 오지 않은 경우 `REPLY_TIMEOUT`)로 돌아옵니다. 제한 시간을 주지 않으면 태스크는 필요한 만큼 계속 기다립니다. 기다리는 시간은 준 틱 수 이상이며 조금 더 길 수 있습니다. 제한 시간은 태스크가 다시 준비 상태가 되는 때를 정할 뿐, 실행되는 때를 정하지는 않습니다. +- **대기 상태**: 실행할 수 있는 태스크가 없어도 커널은 더 이상 멈추지 않습니다. 다음 인터럽트를 기다리다가, 제한 시간이 지난 태스크를 깨우고 계속 진행합니다. 태스크를 깨울 수 있는 것이 아무것도 없으면 기계는 대기 상태로 남고, 부트 로그에 `k0: all tasks stopped (none ready, no timeout pending)`이 찍힙니다. +- **부팅 때 크기를 정하는 커널 표**: 커널은 자신이 쓸 페이지 테이블과 주소 공간 항목의 메모리를 부팅할 때 따로 떼어 둡니다. 크기는 커널이 내어 주는 메모리에 비례합니다(RAM의 약 0.4 %). 그래서 태스크가 이 표들을 다 사용해 버릴 수 없고, 주소 공간의 수는 메모리로만 제한됩니다. - **충돌 격리**: 태스크가 죽거나, 커널이 모르는 시스템 콜을 부르거나, 끝나면 그 태스크만 멈춥니다(폴트 격리). - **태스크 격리와 열쇠 회수**: 서로 다른 열쇠고리와 주소 공간에 묶인 태스크는 서로의 메모리와 열쇠에 닿을 수 없습니다. 모든 열쇠는 어느 열쇠에서 복사됐는지 기억합니다(파생 목록). 열쇠를 회수하거나(CAP_REVOKE) 지우면(CAP_DELETE) 다음 일이 일어납니다. - 거기서 복사한 열쇠도 전부 사라집니다. @@ -226,13 +229,22 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - **자원과 메모리 접근**: 태스크는 열쇠가 없는 자원을 쓸 수 없고, 자기 지도에 없는 메모리를 볼 수 없습니다. > [!WARNING] -> 가용성은 지키지 못합니다. 태스크 하나가 여전히 전체를 멈출 수 있습니다. +> 가용성은 전반적으로 지키지 못합니다. 아래 목록처럼 태스크 하나가 여전히 다른 태스크를 느리게 하거나 막을 수 있습니다. 막지 못하는 것: -- **가용성**: 다음 두 경우가 있습니다. - - 모든 태스크가 메시지를 기다리는 상태가 되면 커널은 프로세서 코어를 세웁니다. 격리된 태스크도 마지막으로 기다리기 시작해서 이 상태를 만들 수 있습니다. - - 빈 메모리를 많이 받은 태스크는 커널의 고정 표(커널 자신이 사용하는 페이지 테이블 40장, 주소 공간 항목 256개)를 다 사용해 버려서 아무도 새 오브젝트를 만들지 못하게 할 수도 있습니다. +- **가용성**: 세 가지는 나아졌지만, 열려 있는 부분이 많습니다. + - 모든 태스크가 기다리고 있어도 커널은 더 이상 멈추지 않습니다. 대기 상태로 있으면서 타이머 틱을 계속 처리합니다. + - 태스크는 타임아웃으로 자기 대기 시간을 제한할 수 있습니다. + - 페이지 테이블과 주소 공간을 위한 커널의 두 표를 태스크가 다 사용해 버릴 수 없게 됐습니다. + + 아직 열려 있는 부분은 다음과 같습니다. + + - 타임아웃 없이 기다리는 태스크는 상대가 끝내 행동하지 않으면 영원히 기다릴 수 있습니다. 타임아웃은 호출마다 주는 것이라서, 계속 응답해야 하는 서버는 모든 대기에 타임아웃을 줘야 합니다. + - 우선순위와 CPU 예산이 없습니다. 태스크는 같은 길이의 시간 조각으로 돌아가며 실행되고, 빈 메모리를 많이 가진 태스크는 태스크를 많이 만들어 다른 태스크의 몫을 줄일 수 있습니다. + - 커널은 시스템 콜을 처리하는 동안 중단할 수 없습니다. 큰 메모리 블록의 열쇠를 회수하는 것 같은 긴 호출은 다른 모든 태스크와 모든 타임아웃을 늦춥니다. + - 커널 안의 치명적 오류, 또는 커널이 한 태스크의 탓으로 돌릴 수 없는 하드웨어 오류는 여전히 기계 전체를 멈춥니다. + - 부트 로그의 커널 부분은 충돌과 종료 줄로 가득 찰 수 있습니다. - **열쇠고리와 주소 공간을 함께 사용하는 태스크**: 이런 태스크끼리는 격리되지 않습니다. 모든 것을 함께 사용하는 한 프로그램의 일부, 즉 스레드처럼 동작합니다. - **태스크 통제**: 어떤 태스크나 그 태스크의 열쇠고리, 주소 공간의 열쇠를 가진 쪽이 그 태스크를 통제합니다. @@ -247,7 +259,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - **케이퍼빌리티 전송**: 메시지에 열쇠를 담아 다른 태스크에 넘기는 기능입니다(IPC를 통한 케이퍼빌리티 전송). - **하드웨어 인터럽트 알림**: 하드웨어 인터럽트를 프로그램에 알려 주는 기능입니다(Notification 오브젝트). - **죽은 태스크 통지**: 죽은 태스크를 멈추기만 하지 않고 처리 담당 태스크에 알려 주는 기능입니다. -- **타임아웃과 멀티코어**: 타임아웃, 그리고 여러 프로세서 코어입니다. +- **멀티코어**: 여러 프로세서 코어입니다. 지금은 코어 하나만 사용합니다. - **장치 접근**: 프로그램이 하드웨어 장치를 쓰게 해 주는 기능입니다(장치 메모리와 인터럽트). - **부팅 뒤 새 실행 코드 적재**: 쓰기와 실행을 함께 허용하지 않는 규칙의 대가입니다. 실행 가능한 메모리는 루트 태스크 이미지에만 있어서 격리된 태스크도 그 이미지의 코드를 실행합니다. - **여러 단계의 열쇠 조회와 ASID**: 여러 단계의 열쇠 조회, 하드웨어 주소 공간 표식(ASID)입니다. 지금은 다른 주소 공간으로 바꿀 때마다 프로세서가 메모리 지도 조회 결과를 담아 두는 캐시(TLB)를 전부 비웁니다. @@ -269,9 +281,9 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. 없는 보호와 보증: -- **가용성 보장**: 앞 절을 참고하세요. +- **가용성 보장**: 앞 절을 참고하세요. 다른 태스크를 막는 길이 여럿 남아 있습니다. - **DMA 격리**: 어떤 장치는 프로세서를 거치지 않고 메모리를 직접 읽고 씁니다(DMA). 장치를 프로그램에 넘기게 되면, 장치용 메모리 지도(IOMMU, 예를 들어 ARM의 SMMU)로 그런 장치가 메모리 전체를 읽지 못하게 막아야 합니다. 이를 위한 것은 아직 없습니다. -- **사이드 채널**: 직접 읽지 않고 실행 시간이나 프로세서가 함께 사용하는 캐시를 통해 비밀이 새는 길입니다. 몇 가지는 막혀 있지만(프로그램은 하드웨어 카운터를 읽을 수 없고, 주소 공간이 바뀔 때마다 TLB를 비움), 캐시나 실행 시간을 이용한 사이드 채널 전반에 대한 대책은 없고 분석도 하지 않았습니다. +- **사이드 채널**: 직접 읽지 않고 실행 시간이나 프로세서가 함께 사용하는 캐시를 통해 비밀이 새는 길입니다. 몇 가지는 막혀 있지만(프로그램은 하드웨어 카운터를 읽을 수 없고, 주소 공간이 바뀔 때마다 TLB를 비움), 타임아웃은 프로그램에 타이머 틱 한 번 정도로 거친 시계를 줍니다. 이것이 공격에 도움이 될 수 있는지는 분석하지 않았습니다. 캐시나 실행 시간을 이용한 사이드 채널 전반에 대한 대책은 없고 분석도 하지 않았습니다. - **대기 중인 송신자**: 열쇠를 회수해도 이미 우편함 앞에서 기다리던 송신자는 취소되지 않습니다. 그 메시지는 한 번 전달됩니다. - **보증의 근거**: 보증은 테스트에서만 나옵니다. - 빌드한 컴퓨터에서의 단위 테스트와 퍼징(무작위로 망가뜨린 입력을 넣어 충돌을 찾는 방법) diff --git a/README.md b/README.md index 2470a0d..9210d43 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ K0 is a small operating system kernel for 64-bit ARM (AArch64) computers. It is ## Security status - **Published version**: the version published as the `v0.1.0` tag has **no isolation between programs**. The published security advisories (public notices about known flaws) apply to it. -- **Development branch**: the current `main` branch (unreleased) keeps programs apart in memory and in the keys they can use. It does **not** protect availability. One program can still bring the whole system to a halt. +- **Development branch**: the current `main` branch (unreleased) keeps programs apart in memory and in the keys they can use. It does **not** protect availability in general. One program can still hold up the others, for example by never giving up a wait. > [!WARNING] > Do not run code you do not trust on K0 anywhere an outage would matter. diff --git a/README_KR.md b/README_KR.md index e42a529..7283674 100644 --- a/README_KR.md +++ b/README_KR.md @@ -18,7 +18,7 @@ K0는 64비트 ARM(AArch64) 컴퓨터용 작은 운영체제 커널입니다. Ru ## 보안 상태 - **공개 버전**: `v0.1.0` 태그로 공개된 버전에는 **프로그램 사이의 격리가 없습니다**. 게시된 보안 어드바이저리(알려진 결함에 대한 공개 공지)가 그대로 적용됩니다. -- **개발 중인 브랜치**: 현재 `main` 브랜치(릴리즈되지 않음)는 메모리와 쓸 수 있는 열쇠를 기준으로 프로그램을 서로 떼어 놓습니다. 하지만 **가용성**은 지키지 못합니다. 프로그램 하나가 여전히 시스템 전체를 멈출 수 있습니다. +- **개발 중인 브랜치**: 현재 `main` 브랜치(릴리즈되지 않음)는 메모리와 쓸 수 있는 열쇠를 기준으로 프로그램을 서로 떼어 놓습니다. 하지만 **가용성**은 전반적으로 지키지 못합니다. 프로그램 하나가 대기를 끝내지 않는 식으로 다른 프로그램을 여전히 붙잡아 둘 수 있습니다. > [!WARNING] > 서비스가 멈추면 곤란한 곳에서는 믿을 수 없는 코드를 K0 위에서 실행하지 마세요. diff --git a/SECURITY.md b/SECURITY.md index 8fe76ce..1ba2407 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -61,9 +61,15 @@ A confined task has the following properties: What is still NOT provided on `main`: -- **Availability**: isolation does not cover it. If every task is blocked the kernel still parks the core (GHSA-q99x-2wrv-358p), and a confined task can cause this by being the last task to block. -- **Kernel resource exhaustion**: a task holding a lot of `Untyped` memory can exhaust the static pool of 40 kernel page tables used for alias mappings, after which `RETYPE` fails with `KERNEL_RESOURCE` for every task, or exhaust the static address space registry. -- **Missing features**: no fault delivery to a handler task, no notifications, no timeouts, and no capability transfer over IPC. +- **Availability**: isolation does not cover it. The kernel no longer halts when every task is blocked, a task can bound its own waits with a timeout (GHSA-q99x-2wrv-358p, see "Known advisories"), and the two kernel tables for alias mappings and address spaces can no longer be exhausted. The following is still open: + - A task that waits without a timeout can wait forever if its partner never acts. A timeout is opt-in per call, so a server or the root task that must stay responsive has to give a timeout on every wait. + - A timeout says when a task becomes ready, not when it runs. There is no priority and no CPU budget. The scheduler is round-robin with a one-tick slice, and a task that holds `Untyped` memory can create many tasks and dilute the share of every other task. + - The kernel is not preemptible. A long system call, for example `CAP_REVOKE` on an `Untyped` with many objects, delays every other task and every timeout. + - A `k0_arch::fatal` or a kernel panic still stops the machine, and so does an SError taken from EL0. + - The kernel part of the boot log can be filled by fault and exit lines. +- **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`. +- **Missing features**: no fault delivery to a handler task, no notifications, and no capability transfer over IPC. +- **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. - **Cores**: one core only. - **Executable code**: new executable code cannot be loaded after boot, so a confined task runs code from the root task image. diff --git a/SECURITY_KR.md b/SECURITY_KR.md index 9bd6daa..cf2982f 100644 --- a/SECURITY_KR.md +++ b/SECURITY_KR.md @@ -61,9 +61,15 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다. `main`에서도 **여전히 제공하지 않는 것**은 다음과 같습니다. -- **가용성**: 격리는 가용성을 보장하지 않습니다. 모든 태스크가 블록되면 커널은 여전히 코어를 정지시키며(GHSA-q99x-2wrv-358p), 격리된 태스크가 마지막으로 블록되는 방식으로 이를 일으킬 수 있습니다. -- **커널 자원 고갈**: `Untyped` 메모리를 많이 가진 태스크는 별칭 매핑에 사용하는 정적 커널 페이지 테이블 풀(40개)을 소진시킬 수 있습니다. 그러면 모든 태스크의 `RETYPE`가 `KERNEL_RESOURCE`로 실패합니다. 정적 주소 공간 레지스트리도 소진시킬 수 있습니다. -- **미구현 기능**: 핸들러 태스크로의 폴트 전달, 알림(notification), 타임아웃, IPC를 통한 케이퍼빌리티 전송이 아직 없습니다. +- **가용성**: 격리는 가용성을 다루지 않습니다. 모든 태스크가 블록되어도 커널은 더 이상 멈추지 않고, 태스크는 타임아웃으로 자신의 대기를 제한할 수 있으며(GHSA-q99x-2wrv-358p, "알려진 어드바이저리" 참고), 별칭 매핑과 주소 공간을 위한 두 커널 테이블은 더 이상 소진되지 않습니다. 다음은 아직 열려 있습니다. + - 타임아웃 없이 기다리는 태스크는 상대가 움직이지 않으면 영원히 기다릴 수 있습니다. 타임아웃은 호출마다 선택하는 기능이므로, 응답성을 유지해야 하는 서버나 루트 태스크는 모든 대기에 타임아웃을 지정해야 합니다. + - 타임아웃은 태스크가 언제 준비 상태가 되는지를 정할 뿐, 언제 실행되는지는 정하지 않습니다. 우선순위와 CPU 예산이 없습니다. 스케줄러는 1틱 슬라이스의 라운드 로빈이며, `Untyped` 메모리를 가진 태스크는 태스크를 많이 만들어 다른 모든 태스크의 몫을 희석시킬 수 있습니다. + - 커널은 선점되지 않습니다. 긴 시스템 콜(예: 오브젝트가 많은 `Untyped`에 대한 `CAP_REVOKE`)은 다른 모든 태스크와 모든 타임아웃을 지연시킵니다. + - `k0_arch::fatal`이나 커널 패닉은 여전히 기계를 멈추며, EL0에서 발생한 SError도 마찬가지입니다. + - 부트 로그의 커널 부분이 폴트 및 종료 줄로 채워질 수 있습니다. +- **커널 자원 고갈**: 커널은 부팅할 때 `Untyped`로 내주는 메모리가 필요로 할 수 있는 페이지 테이블과 주소 공간 레지스트리 항목을 각 범위의 끝에서 떼어 미리 확보합니다. 따라서 `RETYPE`가 페이지 테이블 부족으로 `KERNEL_RESOURCE`와 함께 실패하는 일은 없고, 주소 공간의 수는 메모리로만 제한됩니다. 이 예약분은 4 KiB 그래뉼에서 RAM의 약 0.4 %입니다(페이지 테이블과 등록 항목이 각각 약 0.2 %). 자기 예약분을 담기에 너무 작은 범위는 `Untyped`로 내주지 않습니다. +- **미구현 기능**: 핸들러 태스크로의 폴트 전달, 알림(notification), IPC를 통한 케이퍼빌리티 전송이 아직 없습니다. +- **EL0에서 보이는 시간**: EL0는 여전히 하드웨어 카운터나 타이머를 읽을 수 없습니다. IPC 타임아웃은 태스크에 스케줄러 틱(1초)만큼 거친 시계와 타이머 인터럽트에 맞춰진 깨어남을 제공합니다. 이것이 캐시나 추측 실행 공격에 쓸 만한 시간 원천으로 증폭될 수 있는지는 분석하지 않았습니다. - **revoke 뒤의 송신자**: 엔드포인트에 이미 대기 중인 송신자는 케이퍼빌리티가 revoke된 뒤에도 한 번 전달됩니다. - **코어 수**: 단일 코어만 지원합니다. - **실행 코드**: 부팅 후에는 새 실행 코드를 로드할 수 없으므로, 격리된 태스크는 루트 태스크 이미지의 코드를 실행합니다. diff --git a/USAGE.md b/USAGE.md index 1004c94..38aa57e 100644 --- a/USAGE.md +++ b/USAGE.md @@ -85,7 +85,13 @@ The following table lists the lines that an image with a console driver prints, | `root: ... pass` | One group of self-tests passed | | `root: secret at 0x...`, then `k0: task fault ... far 0x...` with the same address | A confined task tried to read memory that only the root task may see, and it was stopped at exactly that address | | `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 | +| `k0: kernel reserve tables + address space entries = bytes in ranges` | The kernel set aside memory at the top of each range it hands out, for its own page tables and for the list of address spaces. It is printed before the `k0: untyped` lines. On QEMU virt with 512 MiB it reads `262 tables + 130130 address space entries = 0x206000 bytes in 3 ranges`. The entry count depends on the image size | +| `k0: memory + not handed out ()` | A memory range was too small to hold its own share of that reserve, or the share could not be mapped, so the kernel did not hand the range out. The boot continues. A normal run on QEMU virt does not print it | +| `root: timeout tests pass` | The self-tests of IPC timeouts passed | +| `root: kernel reserve tests pass` | The self-tests of the kernel reserve passed (300 address spaces alive at once, and frames made from untyped memory across many page table blocks) | | `root: sched tests pass` | The last group of self-tests passed | +| `k0: idle (waiting for a timeout)` | Every task was waiting and at least one wait had a time limit, so the kernel waited for the next interrupt instead of stopping. It is printed at most once per boot | +| `k0: all tasks stopped (none ready, no timeout pending)` | Every task is waiting and no wait has a time limit. Nothing can wake a task today, so the machine stays idle. A normal run never prints it, and the boot test treats it as a failure. It is printed at most once per boot | | `k0: tick N` | The kernel is still running | Lines such as `root: FAIL`, `k0: FATAL`, `k0: PANIC` or `k0: EXCEPTION` mean that **something went wrong**. The automatic boot test described under "Testing automatically" checks the whole list for you. @@ -264,8 +270,8 @@ $ tools/qemu-boot-test.sh # boot in QEMU and che $ tools/boot-matrix.sh # boot every supported configuration (builds the 16 KiB, pinned and UEFI loader images too) ``` -- `tools/host-test.sh` runs the 221 host tests (161 on an x86-64 computer): small tests of single parts of the kernel (unit tests) as ordinary programs on your computer. It also does **fuzzing**: it feeds the device tree parser and the UEFI loader's planning code random, broken input to find crashes. The 221 are 12 (`k0-abi`), 41 (`k0-cap`), 76 (`k0-boot`), 32 (`k0-efi`) and 30 for each of the two page sizes (`k0-mm`). The memory management tests use ARM instructions, so they run only on an ARM computer (an Apple Silicon Mac or Linux arm64), and the x86-64 count leaves out those 60. -- `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. It prints `boot-test: pass` on success and saves the full log in `target/qemu-boot-test.log`. It takes the machine from the `K0_QEMU_*` variables above. It accepts `K0_BOOT_REUSE=skip` for memory layouts that have no untyped region of the right size, where the root task skips its reuse test. It reads the kernel lines from the **serial port**, so it needs an image with a console driver. For an image without one, see "Testing an image without console" below. If the serial log has no kernel line, it prints a hint about a kernel built without a console feature. +- `tools/host-test.sh` runs the 250 host tests (164 on an x86-64 computer): small tests of single parts of the kernel (unit tests) as ordinary programs on your computer. It also does **fuzzing**: it feeds the device tree parser and the UEFI loader's planning code random, broken input to find crashes. The 250 are 14 (`k0-abi`), 42 (`k0-cap`), 76 (`k0-boot`), 32 (`k0-efi`) and 43 for each of the two page sizes (`k0-mm`). The memory management tests use ARM instructions, so they run only on an ARM computer (an Apple Silicon Mac or Linux arm64), and the x86-64 count leaves out those 86. +- `tools/qemu-boot-test.sh` boots the kernel and reads the log line by line in a fixed order. It fails on any error line, checks the exact number of intentional fault lines, and stops QEMU when it is done. The root task's timeout tests wait for real timer ticks, so a boot takes about 4 seconds longer than it did before they existed. The test also counts the tick lines between `root: teardown tests pass` and `root: timeout tests pass` and wants at least 4, which is how it checks that a timeout does not end early. It prints `boot-test: pass` on success and saves the full log in `target/qemu-boot-test.log`. It takes the machine from the `K0_QEMU_*` variables above. It accepts `K0_BOOT_REUSE=skip` for memory layouts that have no untyped region of the right size, where the root task skips its reuse test. It reads the kernel lines from the **serial port**, so it needs an image with a console driver. For an image without one, see "Testing an image without console" below. If the serial log has no kernel line, it prints a hint about a kernel built without a console feature. - `tools/boot-matrix.sh` boots the kernel in **each** configuration that K0 calls supported and checks the result. It boots QEMU virt with GICv3 and GICv2 at EL1 and EL2, and also three CPU models, 4 cores, the 16 KiB image, other load addresses, `xlnx-versal-virt` and a pinned image. It also checks statically that the image does not touch the physical timer. You can name single rows as arguments. CI runs it. The console rows check the console features. The following table lists the console rows and what they check. @@ -332,6 +338,8 @@ The following table lists what to do for each problem. | The terminal stays blank after `cargo run -p k0-kernel` without features | The image has no console driver and prints nothing. Build with `--features console`, or use `cargo virt` | | `runner: this kernel has no console driver and prints nothing here (build with --features console to see output)` | The image was built without a console feature, or the runner found `k0: console drivers [none]` in it. Build with `--features console` to see output, or read the boot log from memory | | `boot-test: the serial log has no kernel line` | The same cause: a kernel built without a console feature writes nothing to the serial port. Build with `--features console`, or judge the log in guest memory with `K0_BOOT_MEMLOG=` | +| `boot-test` fails on a line that starts with `k0: all tasks` | Every task is waiting and no wait has a time limit, so nothing can wake a task. In the normal self-tests this does not happen. If you changed the root task, give each wait a timeout | +| `k0: memory + not handed out ()` appears in the boot log | The kernel found a memory range that is too small for its own reserve, or whose reserve it could not map. It left that range out and kept booting. The range is simply not usable as untyped memory. Check the memory size and the load address you gave QEMU | | The boot test times out on a slow computer | Give it more time, for example `K0_BOOT_TIMEOUT=300 tools/qemu-boot-test.sh` | | The 16 KiB image does not boot on `cortex-a72` | Expected: that CPU has no 16 KiB page support. Use `K0_QEMU_CPU=max` | | A boot stops early and nothing is printed | There may be no supported console, or the image has no driver for it (an image with only one driver is silent on a console of the other kind). Read the boot log from memory with `tools/boot-log.py` | diff --git a/USAGE_KR.md b/USAGE_KR.md index cb06eb1..9f88c23 100644 --- a/USAGE_KR.md +++ b/USAGE_KR.md @@ -85,7 +85,13 @@ $ grep -a 'k0: console drivers' <이미지 파일> | `root: ... pass` | 자가 테스트 한 묶음이 통과함 | | `root: secret at 0x...` 다음에 같은 주소의 `k0: task fault ... far 0x...` | 격리된 태스크가 루트 태스크만 볼 수 있는 메모리를 읽으려다 정확히 그 주소에서 멈춤 | | `k0: task fault ...`와 `k0: unknown syscall 65535, killing task` | 테스트가 일부러 일으킨 규칙 위반. 매번 규칙을 어긴 태스크만 멈춤. 정상 실행에서는 `k0: task fault` 줄이 정확히 6개, `k0: unknown syscall` 줄이 1개 나옴 | +| `k0: kernel reserve tables + address space entries = bytes in ranges` | 커널이 넘겨 주는 메모리 범위마다 맨 위에 자기 페이지 테이블과 주소 공간 목록용 메모리를 따로 떼어 둠. `k0: untyped` 줄보다 먼저 출력됨. QEMU virt 512 MiB에서는 `262 tables + 130130 address space entries = 0x206000 bytes in 3 ranges`로 나오며, 항목 수는 이미지 크기에 따라 달라짐 | +| `k0: memory + not handed out ()` | 메모리 범위가 너무 작아 그 예비 몫을 담지 못하거나 몫을 매핑하지 못해서, 커널이 그 범위를 넘겨 주지 않음. 부팅은 계속됨. QEMU virt의 정상 실행에서는 나오지 않음 | +| `root: timeout tests pass` | IPC 타임아웃 자가 테스트가 통과함 | +| `root: kernel reserve tests pass` | 커널 예비 공간 자가 테스트가 통과함(주소 공간 300개를 동시에 유지, 여러 페이지 테이블 블록에 걸친 untyped 메모리에서 프레임 생성) | | `root: sched tests pass` | 마지막 자가 테스트 묶음이 통과함 | +| `k0: idle (waiting for a timeout)` | 모든 태스크가 기다리는 중이고 시간 제한이 있는 대기가 하나 이상이어서, 커널이 멈추지 않고 다음 인터럽트를 기다림. 부팅당 최대 한 번 출력됨 | +| `k0: all tasks stopped (none ready, no timeout pending)` | 모든 태스크가 기다리는 중이고 시간 제한이 있는 대기가 없음. 지금은 태스크를 깨울 수 있는 것이 없어서 머신은 유휴 상태로 남음. 정상 실행에서는 나오지 않고, 부팅 테스트는 이 줄을 실패로 처리함. 부팅당 최대 한 번 출력됨 | | `k0: tick N` | 커널이 아직 돌고 있음 | `root: FAIL`, `k0: FATAL`, `k0: PANIC`, `k0: EXCEPTION` 같은 줄은 **문제가 생겼다는 뜻**입니다. "자동 테스트"에서 설명하는 부팅 테스트가 전체 목록을 대신 확인해 줍니다. @@ -264,8 +270,8 @@ $ tools/qemu-boot-test.sh # QEMU에서 부팅하 $ tools/boot-matrix.sh # 지원하는 구성을 전부 부팅(16 KiB 이미지, 고정 이미지, UEFI 로더 이미지도 빌드함) ``` -- `tools/host-test.sh`는 호스트 테스트 221개를 실행합니다(x86-64 컴퓨터에서는 161개). 커널의 부분 하나하나를 내 컴퓨터에서 일반 프로그램처럼 돌리는 작은 테스트(단위 테스트)입니다. **퍼징**도 합니다. 디바이스 트리 파서와 UEFI 로더의 계획 코드에 무작위로 망가뜨린 입력을 넣어 충돌을 찾는 방법입니다. 221개는 `k0-abi` 12개, `k0-cap` 41개, `k0-boot` 76개, `k0-efi` 32개, `k0-mm` 30개씩 두 페이지 크기분입니다. 메모리 관리 테스트는 ARM 명령을 사용하므로 ARM 컴퓨터(Apple Silicon Mac이나 Linux arm64)에서만 돌고, x86-64의 개수는 그 60개를 뺀 것입니다. -- `tools/qemu-boot-test.sh`는 커널을 부팅하고, 로그를 정해진 순서대로 한 줄씩 확인합니다. 에러 줄이 하나라도 나오면 실패하고, 일부러 일으킨 폴트 줄의 개수를 정확히 맞춘 뒤 QEMU를 끕니다. 성공하면 `boot-test: pass`를 출력하고 전체 로그를 `target/qemu-boot-test.log`에 남깁니다. 머신은 앞의 `K0_QEMU_*` 변수에서 가져옵니다. 맞는 크기의 untyped 영역이 없는 메모리 배치에서는 루트 태스크가 재사용 시험을 건너뛰므로, 그때는 `K0_BOOT_REUSE=skip`을 받습니다. 커널 줄을 **직렬 포트**에서 읽으므로 콘솔 드라이버가 있는 이미지가 필요합니다. 콘솔 없는 이미지는 뒤의 "콘솔 없는 이미지 시험"을 보세요. 직렬 로그에 커널 줄이 하나도 없으면 콘솔 feature 없이 빌드한 커널이 아닌지 알려 주는 힌트를 출력합니다. +- `tools/host-test.sh`는 호스트 테스트 250개를 실행합니다(x86-64 컴퓨터에서는 164개). 커널의 부분 하나하나를 내 컴퓨터에서 일반 프로그램처럼 돌리는 작은 테스트(단위 테스트)입니다. **퍼징**도 합니다. 디바이스 트리 파서와 UEFI 로더의 계획 코드에 무작위로 망가뜨린 입력을 넣어 충돌을 찾는 방법입니다. 250개는 `k0-abi` 14개, `k0-cap` 42개, `k0-boot` 76개, `k0-efi` 32개, `k0-mm` 43개씩 두 페이지 크기분입니다. 메모리 관리 테스트는 ARM 명령을 사용하므로 ARM 컴퓨터(Apple Silicon Mac이나 Linux arm64)에서만 돌고, x86-64의 개수는 그 86개를 뺀 것입니다. +- `tools/qemu-boot-test.sh`는 커널을 부팅하고, 로그를 정해진 순서대로 한 줄씩 확인합니다. 에러 줄이 하나라도 나오면 실패하고, 일부러 일으킨 폴트 줄의 개수를 정확히 맞춘 뒤 QEMU를 끕니다. 루트 태스크의 타임아웃 테스트는 실제 타이머 틱을 기다리므로, 부팅 한 번이 그 테스트가 생기기 전보다 약 4초 더 걸립니다. `root: teardown tests pass`와 `root: timeout tests pass` 사이의 틱 줄도 세어 4개 이상을 요구하는데, 이것이 타임아웃이 일찍 끝나지 않는지 확인하는 방법입니다. 성공하면 `boot-test: pass`를 출력하고 전체 로그를 `target/qemu-boot-test.log`에 남깁니다. 머신은 앞의 `K0_QEMU_*` 변수에서 가져옵니다. 맞는 크기의 untyped 영역이 없는 메모리 배치에서는 루트 태스크가 재사용 시험을 건너뛰므로, 그때는 `K0_BOOT_REUSE=skip`을 받습니다. 커널 줄을 **직렬 포트**에서 읽으므로 콘솔 드라이버가 있는 이미지가 필요합니다. 콘솔 없는 이미지는 뒤의 "콘솔 없는 이미지 시험"을 보세요. 직렬 로그에 커널 줄이 하나도 없으면 콘솔 feature 없이 빌드한 커널이 아닌지 알려 주는 힌트를 출력합니다. - `tools/boot-matrix.sh`는 K0가 지원한다고 말하는 **구성마다** 커널을 부팅해서 결과를 확인합니다. GICv3와 GICv2의 QEMU virt를 EL1과 EL2에서 부팅하고, CPU 모델 세 가지, 코어 4개, 16 KiB 이미지, 다른 적재 주소, `xlnx-versal-virt`, 고정 이미지도 부팅합니다. 이미지가 물리 타이머를 건드리지 않는지는 정적으로 검사합니다. 행 이름을 인자로 주면 그 행만 돌립니다. CI가 이것을 실행합니다. 콘솔 행은 콘솔 feature를 확인합니다. 다음 표는 콘솔 행과 확인하는 내용입니다. @@ -332,6 +338,8 @@ GitHub도 풀 리퀘스트와 `main` 푸시가 있을 때마다 이 테스트를 | feature 없이 `cargo run -p k0-kernel`을 하면 터미널이 빈 채로 있음 | 이미지에 콘솔 드라이버가 없어서 아무것도 출력하지 않습니다. `--features console`로 빌드하거나 `cargo virt`를 사용하세요 | | `runner: this kernel has no console driver and prints nothing here (build with --features console to see output)` | 이미지를 콘솔 feature 없이 빌드했거나, 러너가 이미지에서 `k0: console drivers [none]` 줄을 찾았습니다. 출력을 보려면 `--features console`로 빌드하거나 메모리에서 부트 로그를 읽으세요 | | `boot-test: the serial log has no kernel line` | 같은 원인입니다. 콘솔 feature 없이 빌드한 커널은 직렬 포트에 아무것도 쓰지 않습니다. `--features console`로 빌드하거나 `K0_BOOT_MEMLOG=<적재 주소>`로 게스트 메모리의 로그를 판정하세요 | +| `boot-test`가 `k0: all tasks`로 시작하는 줄에서 실패함 | 모든 태스크가 기다리는 중인데 시간 제한이 있는 대기가 없어서 태스크를 깨울 수 있는 것이 없습니다. 기본 자가 테스트에서는 일어나지 않습니다. 루트 태스크를 바꿨다면 대기마다 타임아웃을 지정하세요 | +| 부트 로그에 `k0: memory + not handed out ()`가 나옴 | 커널이 자기 예비 공간을 담기에 너무 작거나 그 몫을 매핑하지 못하는 메모리 범위를 찾았습니다. 그 범위를 제외하고 부팅을 계속했으며, 해당 범위는 untyped 메모리로 쓸 수 없습니다. QEMU에 준 메모리 크기와 적재 주소를 확인하세요 | | 느린 컴퓨터에서 부팅 테스트가 시간 초과 | 시간을 늘리세요. 예: `K0_BOOT_TIMEOUT=300 tools/qemu-boot-test.sh` | | 16 KiB 이미지가 `cortex-a72`에서 부팅되지 않음 | 정상입니다. 그 CPU는 16 KiB 페이지를 지원하지 않습니다. `K0_QEMU_CPU=max`를 사용하세요 | | 부팅이 일찍 멈추고 아무것도 출력되지 않음 | 지원하는 콘솔이 없거나, 이미지에 그 콘솔의 드라이버가 없을 수 있습니다(드라이버가 하나뿐인 이미지는 다른 종류의 콘솔에서 조용합니다). `tools/boot-log.py`로 메모리에서 부트 로그를 읽으세요 | diff --git a/assets/exception-paths.svg b/assets/exception-paths.svg index 0fe9275..ace34e4 100644 --- a/assets/exception-paths.svg +++ b/assets/exception-paths.svg @@ -66,6 +66,7 @@ Acknowledge Timer: re-arm 1 s, tick k0_preempt + Expires timeouts first diff --git a/assets/exception-paths_KR.svg b/assets/exception-paths_KR.svg index 2bd82b6..3d7fa43 100644 --- a/assets/exception-paths_KR.svg +++ b/assets/exception-paths_KR.svg @@ -66,6 +66,7 @@ 인터럽트 확인 타이머: 1초 뒤 재설정, tick k0_preempt + 먼저 타임아웃 만료 diff --git a/assets/scheduling-states.svg b/assets/scheduling-states.svg index d991d10..eabf54d 100644 --- a/assets/scheduling-states.svg +++ b/assets/scheduling-states.svg @@ -1,6 +1,6 @@ Task states and transitions - Inactive becomes Stopped through TCB_CONFIGURE and Ready through TCB_RESUME, round robin moves a task between Running and Ready, a task blocks in IPC and becomes Ready when released, and teardown makes it Dead from any state. + Inactive becomes Stopped through TCB_CONFIGURE and Ready through TCB_RESUME, round robin moves a task between Running and Ready, a task blocks in IPC and becomes Ready when released by its partner or when its deadline passes, and teardown makes it Dead from any state. bytes in ranges` | `reserve_kernel_share` carves the kernel share out of each free physical range before any untyped capability exists (see "Carving the kernel share out of untyped memory"). A range that cannot hold its share is not handed out, and the kernel prints the first kind of line with the reason. The second line is printed once, for example `k0: kernel reserve 262 tables + 130130 address space entries = 0x206000 bytes in 3 ranges` on QEMU virt with 512 MiB and the 4 KiB granule. | +| `k0: untyped ...`, `k0: root cnode ready (N caps, N untyped, N image frames, N slots)` | The root CNode (an object in the window with `ROOT_CNODE_SLOTS` = 512 slots, as the log shows) is filled: slot 1 the root TCB, slot 2 the root address space, slot 3 the console, slot 4 the root CNode itself, then every free physical range that was handed out as an untyped capability, then one Frame capability per mapped granule of the root task image (text with R and X, read-only data with R, data with R and W). Finally the root task is bound to its CNode and address space, exactly as any other task is: copies of those two capabilities go into its TCB. See [capabilities.md](capabilities.md). | | `k0: bootinfo page ready` | The capability list is written into the read-only bootinfo page: a header and one descriptor per slot, with the VA, size and rights of every image Frame. | | `k0: user w^x checks pass` | `TTBR0` now points at the user tables, the identity map is gone, and the user mappings are checked from both EL0 and EL1. | | `k0: device pages [...] of 0x1000 bytes` | Every device page the kernel keeps mapped. After this line the kernel maps no further device. | @@ -132,6 +133,18 @@ In the following table, each row gives a log line and the step it stands for, in - **Contents**: the window holds the root task image, its stack, its page tables, the bootinfo page, the root TCB and the root CNode. - **Excluded from untyped**: the window is excluded from the untyped capabilities, so the root task can never retype memory the kernel is still using. +### Carving the kernel share out of untyped memory + +`reserve_kernel_share` in `kernel/src/main.rs` runs after the root task is loaded and before the untyped capabilities are made. For each free physical range it works as follows: + +- **Share**: it computes the largest number of page tables that mapping every granule of the range can need (`k0_mm::alias_tables_for`) and the number of granules for one 8-byte address space entry per granule of the range. +- **Placement**: it takes that share from the top of the range. The tables become the table reserve (`k0_mm::reserve_tables`) and the entries become the address space registry for the range (`add_range`). The entry area is mapped into the kernel alias window and zeroed. Tables from the reserve are zeroed when they are handed out, not at boot. +- **Result**: the range that remains, without its share, is handed out as one `Untyped` capability. After boot, `alias_object` takes its tables from the reserve, so a task cannot use them up. +- **A range that cannot hold its share**: a range that is too small, or whose share cannot be mapped, is not handed out as `Untyped` at all. The kernel prints `k0: memory + not handed out ()` and continues. A range that does not fit in the buffer of ranges is skipped the same way (`too many ranges`). +- **A gap without a whole granule**: it is handed out unchanged, because no object can be made from it and it needs no share. + +This step **never refuses to boot**. The worst case is that memory is not handed out and a log line says so. The overhead is about 0.2 % of RAM with the 4 KiB granule and about 0.05 % with the 16 KiB granule. The root task's address space has its root table in the boot window and uses one dedicated registry entry. + ### After the handoff `handoff` records the root task as the running task and points the vector code at its saved context. `enter_user` then masks all exceptions (`DAIFSet`), rewinds the kernel stack to the top, and returns to EL0 through the same path every later return uses. **The mask comes first** because that path writes `ELR_EL1` and `SPSR_EL1` before `eret`. The boot path has already unmasked the timer, and an interrupt in between would overwrite both registers with EL1 values. From then on, kernel code runs only in response to an exception: a system call, a fault, or the timer interrupt. [exceptions.md](exceptions.md) describes that path. diff --git a/design/en/capabilities.md b/design/en/capabilities.md index 904359f..03ca7e0 100644 --- a/design/en/capabilities.md +++ b/design/en/capabilities.md @@ -47,6 +47,7 @@ Capabilities are stored as raw words and decoded with validation on every use. A - rights on a kind that has none - stray bits - a mapping record on an unmapped capability +- an address space id (`asid`) that is 0 or larger than the greatest granule number a slot can hold - an empty slot that is still linked into a list > [!IMPORTANT] @@ -119,17 +120,19 @@ The root task's CNode is the root CNode. It has `ROOT_CNODE_SLOTS` (512) slots a The image `Frame` capabilities have rights fixed by the segment: text is `R|X` (no `W`), read-only data is `R`, data is `R|W` (no `X`). The text frames are the only frames in the system that carry `X`, and their contents are the image whose hash was verified at boot. The root task's own boot mappings are permanent and are not represented by these capabilities. -The untyped capabilities cover every byte of RAM reported by the device tree, minus every reserved range. The kernel passes these reserved ranges: +The untyped capabilities cover every byte of RAM reported by the device tree, minus every reserved range, minus the kernel's own share of each range (see below). The kernel takes these reserved ranges out: - the kernel image - the DTB - the 2 MiB boot frame window - every firmware reserved range from the DTB, both the memory reservation block and the children of `/reserved-memory` -Reserved ranges may overlap one another and may arrive in any order. For each memory region, a cursor walks forward through the reserved ranges in address order and emits the gaps between them. So overlapping reservations simply merge. +Reserved ranges may overlap one another and may arrive in any order. Before the root CNode is filled, the kernel checks the regions with `check_regions`. For each memory region, `for_each_gap` then walks a cursor forward through the reserved ranges in address order and emits the gaps between them. So overlapping reservations simply merge. + +From the top of each gap, the kernel then takes its own share: the page tables for the kernel alias and the address space registry entries (see [memory.md](memory.md) and [user-address-space.md](user-address-space.md)). `bootstrap` receives the ranges that are left, already carved, and makes one `Untyped` capability of each. A gap that cannot host its share is not handed out, and the kernel prints `k0: memory + not handed out ()`. > [!IMPORTANT] -> Memory regions themselves must not overlap. If two regions overlapped, the same physical frame would sit in two untyped capabilities and could be retyped into two different objects. `bootstrap` rejects such a map, and the kernel stops booting. +> Memory regions themselves must not overlap. If two regions overlapped, the same physical frame would sit in two untyped capabilities and could be retyped into two different objects. `check_regions` rejects such a map, and the kernel stops booting. Running out of slots also stops the boot. A DTB memory region beyond the CPU's physical address width stops the boot as well. @@ -162,11 +165,11 @@ The checks run in the following order, and the order is the important part. 5. If the untyped has no descendants, the watermark restarts at the base (memory reuse, see below). 6. The rounded watermark plus one granule must fit inside the untyped range, with every addition checked for overflow, and the object's physical address must be encodable in a slot. Otherwise `EXHAUSTED`. 7. The new capability's derivation depth must stay within `MAX_DEPTH`, otherwise `TOO_DEEP`. -8. Only then does the kernel prepare the memory. The callback in `sys_retype` maps the granule into the kernel alias (see [memory.md](memory.md); re-mapping an identical alias is accepted) and zeroes it. For an `ADDR_SPACE` it also registers the new address space in the registry. A failure here returns `KERNEL_RESOURCE`. +8. Only then does the kernel prepare the memory. The callback in `sys_retype` maps the granule into the kernel alias (see [memory.md](memory.md); re-mapping an identical alias is accepted) and zeroes it. For an `ADDR_SPACE` it also registers the new address space in the registry. The tables and the registry entry come from the reserve that the kernel set aside at boot, so a granule inside an `Untyped` capability that the kernel handed out always has both. A failure here would return `KERNEL_RESOURCE`, but no known cause remains. 9. Only if the preparation succeeds does the watermark move and the new capability go into the destination slot. > [!IMPORTANT] -> If any step fails, nothing has changed. The watermark, the destination slot, the registry and the kernel table pool are exactly as before, and the caller gets an error code. The memory is zeroed before the capability exists, so no task can observe the previous contents of retyped memory. +> If any step fails, nothing has changed. The watermark, the destination slot, the registry and the kernel tables are exactly as before, and the caller gets an error code. The memory is zeroed before the capability exists, so no task can observe the previous contents of retyped memory. Zeroing is a security step and a design choice at the same time. It keeps previous contents from leaking into the new object, and it means a zeroed frame already is a valid initial object. In the following table, you can see how each zeroed object is interpreted. @@ -232,7 +235,7 @@ When an original capability is removed, its object is finalized by the callbacks - **Tcb** (original), and any capability bound to a task: the task is torn down, see [scheduling.md](scheduling.md) and [ipc.md](ipc.md). - **AddrSpace** (original): it is released in the registry (which bumps its generation). If it is installed in TTBR0, TTBR0 is switched to an empty table from the kernel pool. -A **mapping record** is `(id, generation, va, level)`. Unmapping, deleting and revoking only walk a root that the registry confirms is still the same address space, and only clear an entry that still points at that very frame or table. See [user-address-space.md](user-address-space.md). +A **mapping record** is `(asid, generation, va, level)`. The `asid` is the number of the granule that holds the root table of the address space, a `u64` (the same number as in `Cap::AddrSpace`). It is checked when the word is decoded. Unmapping, deleting and revoking only walk a root that the registry confirms is still the same address space, and only clear an entry that still points at that very frame or table. See [user-address-space.md](user-address-space.md). **No recursion**. A CNode or a TCB holds slots, so finalizing one means deleting what it holds, which may finalize more containers. k0-cap does not recurse. It links the slot array of a finalized container onto a pending list, threaded through the array's slot 0, and the same call drains the list in a loop. Kernel stack use does not grow with derivation depth or CNode nesting. Time is proportional to the number of capabilities removed, and interrupts are masked meanwhile. @@ -278,7 +281,7 @@ The following table lists the error codes for slot problems and their meaning. | `BAD_BADGE` | a badge on a kind that cannot carry one, or a different badge on an already badged capability | | `TOO_DEEP` | the derivation depth limit would be exceeded | | `REVOKED` | returned to a task that was waiting on an endpoint that was deleted | -| `KERNEL_RESOURCE` | an internal pool is exhausted (kernel table pool for alias mappings, address space registry) | +| `KERNEL_RESOURCE` | an internal resource is missing. It is still a defined code, but neither the kernel alias tables nor the address space registry can cause it any more | ## How it is tested @@ -325,9 +328,9 @@ The 16 KiB image boots and passes the boot checks on QEMU `-cpu max`, and it boo ## Known gaps > [!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, fault delivery to a handler task and timeouts are not in the model yet, and there is one core. +> 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. If every task is blocked, the kernel still parks the core (see GHSA-q99x-2wrv-358p in [SECURITY.md](../../SECURITY.md)), and a confined task can cause this by blocking last. A task that holds a lot of untyped memory can exhaust the static pool of 40 kernel page tables used for alias mappings, or the address space registry. Then `RETYPE` fails with `KERNEL_RESOURCE` for everyone. +- **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. - **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). diff --git a/design/en/exceptions.md b/design/en/exceptions.md index 440d168..465b3fe 100644 --- a/design/en/exceptions.md +++ b/design/en/exceptions.md @@ -43,7 +43,9 @@ The fatal vector path above is for exceptions the CPU raises. `k0_arch::fatal` i ### Interrupts while in the kernel -An IRQ taken at EL1 saves the caller-saved registers on the kernel stack, calls the handler and returns. After the handoff this does not happen, because exception entry masks interrupts and the kernel never unmasks them while handling an exception. The kernel itself is never preempted. +An IRQ taken at EL1 saves the caller-saved registers on the kernel stack, calls the handler and returns. While the kernel handles an exception it keeps interrupts masked, with one exception: the idle wait in `idle_until_ready` (see [The finish path](#the-finish-path)). The kernel itself is never preempted. + +The idle wait opens only the I bit, for one pending interrupt, by `k0_arch::irq::wait_for_interrupt` (`wfi` with IRQs masked, then a short unmask). This is safe for three reasons. First, the whole EL0 context, including `ELR_EL1` and `SPSR_EL1`, is already saved in the TCB, so the nested EL1 IRQ may overwrite both registers without losing anything. Second, the handler runs on the kernel stack, which has plenty of room because the exception entry starts at the top of it. Third, the mask is set again right after the interrupt, so no other kernel code runs with interrupts open. ### Vectors at EL2 @@ -120,16 +122,25 @@ It then calls `kill_current`, which runs the teardown described in [scheduling.m 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: -1. **The current task is Dead**: no return value is written into its context. The context is zeroed, so no register of a dead task survives, and the kernel switches to the next ready task. If none is ready, it prints `k0: all tasks exited` and parks. +1. **The current task is Dead**: no return value is written into its context. The context is zeroed, so no register of a dead task survives, and the kernel switches to the next ready task. If none is ready, it calls `idle_until_ready` (see below). 2. **Any other case**: the return value is written to `x0`. IPC calls that block write their results later, when the partner acts. Cleanup comes before the switch because a revoke can destroy the very address space or CNode the task was using. The next task must not run on top of half-finished cleanup. +When no task is ready (for example the last runnable task died, or every task is blocked), `idle_until_ready` **keeps the kernel idle instead of stopping it**. In a loop it waits for the next interrupt with `k0_arch::irq::wait_for_interrupt`, calls `k0_ipc::expire_timeouts` so that every IPC waiter whose deadline has passed is woken, and switches to a ready task if there is one. Timer ticks keep being counted and handled while the kernel idles. The nested EL1 IRQ is explained in [Interrupts while in the kernel](#interrupts-while-in-the-kernel). The function prints two lines, each at most once per boot: + +| Line | When | +| --- | --- | +| `k0: idle (waiting for a timeout)` | the first time the kernel idles while at least one waiter has a deadline | +| `k0: all tasks stopped (none ready, no timeout pending)` | the first time the kernel idles while no waiter has a deadline | + +In the second state nothing can wake a task today, because there are no notification objects and no device interrupts for tasks. The machine stays idle. `tools/qemu-boot-test.sh` treats any line that starts with `k0: all tasks` as a failure. + ## Timer interrupts from EL0 The only interrupt the kernel enables is **the EL1 virtual timer**. Its interrupt number comes from the DTB, and the kernel uses no physical timer. The interrupt controller is GICv2 or GICv3, whichever the DTB says is the timer's interrupt parent. Before it writes anything, the driver checks the identification registers against that description and refuses to boot if they differ. See [dtb.md](dtb.md). -An IRQ taken from EL0 is saved the same way as a system call. The handler acknowledges the interrupt. If it was the timer, it re-arms the timer for one second, and prints `k0: tick N`. In an image built with a console driver, the line also goes to the console; only the first 4 tick lines are logged. Then it calls `k0_preempt`, which rotates to the next ready task. Spurious interrupt numbers 1020 to 1023 are ignored. Any other interrupt number, or any FIQ, cannot happen by design, so the kernel prints `k0: UNEXPECTED ...` and parks. +An IRQ taken from EL0 is saved the same way as a system call. The handler acknowledges the interrupt. If it was the timer, it re-arms the timer for one second, and prints `k0: tick N`. In an image built with a console driver, the line also goes to the console; only the first 4 tick lines are logged. Then it calls `k0_preempt`. That function first expires the IPC timeouts that are due (`k0_ipc::expire_timeouts`), so a waiter whose deadline has passed is ready before the round-robin switch, and then rotates to the next ready task. Spurious interrupt numbers 1020 to 1023 are ignored. Any other interrupt number, or any FIQ, cannot happen by design, so the kernel prints `k0: UNEXPECTED ...` and parks. ## How it is tested @@ -145,5 +156,6 @@ The test also requires the ordered markers, among them `k0: task fault dabort-lo > 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. - 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, but if it was the last runnable task **the whole system parks** (`k0: all tasks exited`). If all tasks are blocked, the kernel also parks (GHSA-q99x-2wrv-358p). Isolation does not cover availability. +- 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. +- The whole system still stops in these cases: `k0_arch::fatal` and the fatal vector path, a kernel panic, an SError taken from EL0, and a trap to EL2. - The fault message **includes user addresses**. That is useful for debugging, but it goes to the boot log and, in an image built with a console driver, to the console. Every task holding a `Console` capability can also write to both. diff --git a/design/en/hardening.md b/design/en/hardening.md index 2e90fea..38d927e 100644 --- a/design/en/hardening.md +++ b/design/en/hardening.md @@ -80,6 +80,8 @@ The bootloader may leave registers in states that let user space observe or cont A trap at EL0 is handled as a fault, and the task is terminated (see [exceptions.md](exceptions.md)). The only exception is `WFI` and `WFE`, which the kernel skips. Trapping FP/SIMD means the kernel never has to save vector registers, so a task can never read vector state left behind by another task. +EL0 still cannot read any hardware counter or timer. IPC timeouts, however, give EL0 **a clock that is as coarse as the scheduler tick** (one second), together with a wake-up that is aligned to the timer interrupt (see [ipc.md](ipc.md)). The **tick period is therefore a side-channel decision**. Whether this clock can be amplified into a useful timing source for cache or speculation attacks has not been analysed. + The EL0 thread pointer registers `TPIDR_EL0` and `TPIDRRO_EL0` are part of each task's saved context. `TCB_CONFIGURE` zeroes them, so a new task starts without the creator's values. `DEBUG_PUTC` requires the `Console` capability and replaces every byte that is neither printable ASCII nor a newline with `?`. A task cannot send terminal escape sequences to whoever reads the console (in an image built with a console driver) or the boot log. diff --git a/design/en/ipc.md b/design/en/ipc.md index ec0cb81..38b030e 100644 --- a/design/en/ipc.md +++ b/design/en/ipc.md @@ -53,7 +53,15 @@ A sender that has to wait in the queue keeps the badge of its send in its TCB (` ## The four calls -All four take an `Endpoint` capability in `x0` and flags in `x1`. The only flag is `NONBLOCK`: if the other side is not ready, the call returns `WOULD_BLOCK` instead of waiting. There are no timeouts, so `NONBLOCK` is the only way not to wait. The following figure shows the order of `CALL` and `REPLY_RECV` in the case where the server waits in `RECV` first. +All four take an `Endpoint` capability in `x0` and flags in `x1`. The flags register has the following layout: + +| Bits | Name | Meaning | +| --- | --- | --- | +| 0 | `NONBLOCK` | if the other side is not ready, the call returns `WOULD_BLOCK` instead of waiting | +| 31 to 1 | reserved (`k0_abi::ipc::RESERVED`) | must be 0 | +| 63 to 32 | timeout | the longest wait in scheduler ticks, 0 means wait forever (see [Timeouts](#timeouts)) | + +`k0_abi::ipc::timeout(ticks)` builds the timeout value, and `k0_abi::ipc::TIMEOUT_SHIFT` is 32. `NONBLOCK` wins over a timeout. A call with any reserved bit set fails with `BAD_FLAGS` before anything else is looked at. For `REPLY_RECV`, this happens before the pending reply is consumed. The following figure shows the order of `CALL` and `REPLY_RECV` in the case where the server waits in `RECV` first.

When the server is already waiting in RECV, the CALL of the client delivers the message and the badge to the server and blocks the client in BlockedReply, and REPLY_RECV of the server wakes the client with the one-time reply right @@ -67,7 +75,7 @@ The four calls work as follows. **CALL** sends a message and waits for the reply in a single trap. If a receiver is waiting, the message is delivered and the caller moves straight to `BlockedReply`. Otherwise the caller waits in the queue as `BlockedCall`. Either way, **the caller always blocks**. Because sending and waiting happen in one step, the reply can never arrive in the gap between them. -**REPLY_RECV** is the server loop in one trap. If the calling task holds a reply right, the kernel delivers `x2` to `x5` as the reply to the waiting caller, makes the caller ready, and drops the right. Then it continues exactly like `RECV`. +**REPLY_RECV** is the server loop in one trap. If the calling task holds a reply right, the kernel delivers `x2` to `x5` as the reply to the waiting caller, makes the caller ready, and drops the right. Then it continues exactly like `RECV`, including a timeout, which applies to this receive phase only. The endpoint is checked first. If the endpoint capability is invalid or lacks `R`, the call fails without using up the reply. The reply is delivered with `x1 = 0`. @@ -97,20 +105,61 @@ The teardown looks only at the task's state and cuts every kernel pointer to it: - **Holding a reply right**: the caller waiting for it wakes with `NO_REPLY`. - **Inactive, stopped or running**: nothing to unlink. -The state then becomes `Dead` and the saved registers are zeroed. If the task that made the system call is the one that died, the kernel never writes a return value into it and switches to the next ready task. +A task that waits with a deadline is also removed from the timed list of the scheduler. The state then becomes `Dead` and the saved registers are zeroed. If the task that made the system call is the one that died, the kernel never writes a return value into it and switches to the next ready task. When the original capability of an endpoint is deleted, every task still queued on it wakes with `REVOKED`, and no TCB points at the endpoint afterwards. Deleting only a copy of the capability does not touch the queue. +## Timeouts + +Every wait can be bounded. A timeout is the upper 32 bits of the flags register `x1`, counted in scheduler ticks. The tick period is 1 second (a kernel constant), so the tick is the unit of every timeout. The following rules apply. + +- **Deadline rule**: a timeout of n ticks ends at the (n+1)-th timer tick after the call. As long as ticks are handled on time, the wait lasts between n and n+1 tick periods. +- **Lower bound, not wall-clock time**: the kernel runs with interrupts masked during every system call, and a long one such as a large `CAP_REVOKE` makes a tick late. The wait is then that much longer. +- **0 means no deadline**: the task waits until its partner acts, as before. +- **One deadline for a call**: the deadline of `CALL` covers both phases, waiting for a receiver and then waiting for the reply. +- **Reply and receive**: `REPLY_RECV` applies the timeout to its receive phase only. + +The following table lists what the caller gets when a wait ends by timeout. + +| Call | Where it waited | Result | What happened to the message | +| --- | --- | --- | --- | +| `SEND` | in the endpoint queue | `TIMEOUT` | not delivered | +| `RECV`, `REPLY_RECV` | in the endpoint queue | `TIMEOUT` | nothing received (a reply given by `REPLY_RECV` was already delivered) | +| `CALL` | in the endpoint queue | `TIMEOUT` | not delivered | +| `CALL` | `BlockedReply` | `REPLY_TIMEOUT` | delivered, and the server may or may not have acted | + +When a `CALL` ends with `REPLY_TIMEOUT`, the kernel clears the reply right of the server that holds it. If the server answers later, its `REPLY_RECV` finds no reply right to use, and the late reply is dropped. The next caller receives its own reply. + +### The timed list + +Each TCB has the fields `deadline`, `tnext` and `tprev`. `k0-sched` keeps an unsorted, intrusive list of the timed waiters (`arm_timeout`, `disarm_timeout`, `expired`, `has_timed`), plus a lower bound of the earliest deadline so that most ticks do not walk the list. A task leaves a blocked state in only two ways, and both remove it from the list: + +- `k0_sched::enqueue` (a wake-up), so a waiter woken by a message keeps no deadline, and +- `k0_ipc::teardown` (death). + +`k0_ipc::expire_timeouts` handles the expired waiters. It removes a waiter from its endpoint queue and wakes it with `TIMEOUT`, or it clears the reply link of the task that holds its reply and wakes it with `REPLY_TIMEOUT`. A link that does not match the state halts the kernel with `k0: FATAL`, as in teardown. It runs on every timer tick: + +- from `k0_preempt`, when a task was running, and +- from the idle loop, when none was. + +The walk costs O(number of timed waiters) with interrupts masked, at most once per tick. + +> [!NOTE] +> EL0 still cannot read any hardware counter or timer. A timeout gives EL0 a clock as coarse as the scheduler tick and a wake-up aligned to the timer interrupt. Whether that can be amplified into a useful timing source for cache or speculation attacks has not been analysed. + ## Blocking and deadlock -A task that has to wait is marked with its blocked state and linked into the endpoint queue or held by a reply right. Then the scheduler switches to the next ready task (see [scheduling.md](scheduling.md)). Its return registers are written later, by the task that releases it. +A task that has to wait is marked with its blocked state and linked into the endpoint queue or held by a reply right. If the call has a timeout, the task is also put in the timed list. Then the scheduler switches to the next ready task (see [scheduling.md](scheduling.md)). Its return registers are written later, by the task that releases it. + +If no task is ready at that point, the kernel does not stop. It idles in `idle_until_ready` (`kernel/src/syscall.rs`): it waits for the next interrupt, wakes every waiter whose deadline has passed, and switches to a ready task if there is one. Timer ticks keep being counted and handled meanwhile. The idle loop prints one of two lines, each at most once per boot: -If no task is ready at that point, every task is blocked and nothing can ever wake one, because K0 does not yet have notification objects for interrupts. The kernel prints `k0: all tasks blocked` and parks the core. +- `k0: idle (waiting for a timeout)`: at least one waiter has a deadline, so something will wake a task. +- `k0: all tasks stopped (none ready, no timeout pending)`: no waiter has a deadline. Nothing can wake a task in that state today, because K0 has no notification objects and no device interrupts for tasks, so the machine stays idle. `tools/qemu-boot-test.sh` treats any line that starts with `k0: all tasks` as a failure. > [!WARNING] -> Stopping the whole system is the fail-secure choice here, but it is also advisory GHSA-q99x-2wrv-358p in [SECURITY.md](../../SECURITY.md): one task can halt the machine by blocking last. A confined task that holds a capability to an endpoint can still do it, and isolation does not cover availability. +> 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. -This is unchanged by task isolation. +A server, or the root task, that must stay responsive has to give a timeout on every wait. Task isolation does not change this. ## Errors @@ -124,6 +173,9 @@ The following table lists the error codes and their causes. | `WOULD_BLOCK` | `NONBLOCK` was set and the other side was not ready | | `NO_REPLY` | the receiver of a `CALL` exited, faulted or took a newer `CALL` without replying, or was destroyed | | `REVOKED` | the original capability of the endpoint was deleted while the caller was queued on it | +| `TIMEOUT` | the wait ended before a partner arrived, and the message was not delivered | +| `REPLY_TIMEOUT` | a `CALL` was delivered but no reply came in time, and the server may or may not have acted | +| `BAD_FLAGS` | a reserved bit (31 to 1) of the flags register was set | ## How it is tested @@ -136,6 +188,17 @@ IPC and teardown are tested by booting. The root task starts a server task and c - a server that receives a new `CALL` while it still holds a reply right, so that the first caller gets `NO_REPLY`, and - a server that exits while a caller waits, so that the caller gets `NO_REPLY`. +The timeout tests (`test_timeouts` in `userspace/root-task/src/main.rs`) wait for real ticks and check the following: + +- that reserved flag bits are refused, and that `NONBLOCK` beats a timeout, +- a `CALL` whose server never answers, which returns `REPLY_TIMEOUT` while every other task is blocked too, +- three waiters in `RECV`, `SEND` and `CALL`, which return `TIMEOUT`, +- that the late reply of the server is dropped and the next call gets its own reply, +- that a timed waiter can be deleted, and +- that a waiter woken by a message keeps no deadline. + +The timeout tests take their objects from the largest untyped. The tests wait for real ticks, so a boot test takes about 4 seconds longer. + The capability tests check that a badge can be set once and is refused a second time, that a copy keeps the badge, that a send-only capability cannot receive and a receive-only one cannot send (`NO_RIGHTS`), and that revoking an endpoint removes every copy while the original stays. The isolation tests start a confined task whose CNode holds only a send-only, badged endpoint capability. The root task checks that the task receives the badge it was given in `x1` and that slot numbers of the root task mean nothing in the confined CNode (`BAD_SLOT`). @@ -151,12 +214,16 @@ The teardown tests delete tasks in each state and check the queues afterwards: The boot test script also requires an exact number of `k0: task fault` lines and exactly one `k0: unknown syscall` line, so a task that keeps running after it was destroyed fails the test. -`tools/qemu-boot-test.sh` requires `root: ipc tests pass`. +`tools/qemu-boot-test.sh` requires `root: ipc tests pass`, `k0: idle (waiting for a timeout)` and `root: timeout tests pass`. When it judges by the serial port, it also counts the timer tick lines between `root: teardown tests pass` and `root: timeout tests pass`. There must be at least 4, which is how the lower bound of a timeout is checked, because EL0 has no clock. ## Known gaps > [!NOTE] -> Capability transfer over IPC does not exist yet. Notifications and timeouts do not exist yet either, so a blocked task waits until its partner acts. +> Capability transfer over IPC and notification objects do not exist yet. Timeouts are opt-in per call, so a task that waits without one still waits until its partner acts. +- **Timeouts say when a task becomes ready, not when it runs**: there is no priority and no CPU budget, and the scheduler is round robin with a one-tick slice (see [scheduling.md](scheduling.md)). +- **Long system calls**: the kernel is not preemptible, so a long call such as `CAP_REVOKE` on an untyped with many objects delays every other task and every timeout. +- **Fatal stops**: a `k0_arch::fatal` or a kernel panic still stops the machine. +- **Timing source for EL0**: whether the tick-aligned wake-up can be used for timing attacks has not been analysed. - **A queued sender**: it delivers once after revocation. A sender that is already waiting on an endpoint keeps the badge of the send that queued it. If its capability is revoked while it waits, its message is still delivered once to the next receiver. - **Four words per message**: larger data needs shared memory. The holder of a task's `AddrSpace` capability must map it into that task's address space, since tasks can now run in separate address spaces. diff --git a/design/en/memory.md b/design/en/memory.md index cb59e8c..0622c81 100644 --- a/design/en/memory.md +++ b/design/en/memory.md @@ -6,7 +6,7 @@ English | [한국어](../kr/memory_KR.md) -This note describes how the kernel maps itself: the translation setup, the static table pool, the permission scheme, and the checks that confirm the result at boot. The code is in `crates/k0-mm/src/paging.rs`. User address spaces are covered in [user-address-space.md](user-address-space.md). +This note describes how the kernel maps itself: the translation setup, the static table pool and the table reserve, the permission scheme, and the checks that confirm the result at boot. The code is in `crates/k0-mm/src/paging.rs`. User address spaces are covered in [user-address-space.md](user-address-space.md). ## Two halves @@ -35,12 +35,12 @@ The kernel maps **only pages**, never blocks. Every mapping goes through the sam ## The static table pool -The kernel has no heap. Its page tables come from a **pool of 40 tables** in `.bss`, handed out by a counter that only goes up. Three tables are taken when the MMU is set up: +The kernel has no heap. During boot, its page tables come from a **pool of 40 tables** in `.bss`, handed out by a counter that only goes up. Three tables are taken when the MMU is set up: - the roots of the two halves (two tables) - an empty `TTBR0_EL1` root with no mappings in it (`null_user_root`) -The kernel switches `TTBR0_EL1` to that empty root when the address space that is currently installed is destroyed, so the hardware never walks a table that no longer exists. The rest become intermediate tables as mappings are added. On QEMU virt with the default build, the boot log line `k0: kernel table pool N/40`, printed after the boot frame window is mapped, shows `16/40`. Later `RETYPE` calls can use more. +The kernel switches `TTBR0_EL1` to that empty root when the address space that is currently installed is destroyed, so the hardware never walks a table that no longer exists. The rest become intermediate tables as mappings are added. On QEMU virt with the default build, the boot log line `k0: kernel table pool N/40`, printed after the boot frame window is mapped, shows `16/40`. The pool is used only during boot. After boot, the tables for `RETYPE` come from the table reserve (see "The table reserve"). When the walk follows an existing table entry, `index_of` converts the address in that entry back into a pool index. It rejects any address that does not land exactly on an allocated table in the pool. A corrupted or forged table address therefore stops the walk with `BadTable`. It is never followed into arbitrary memory. @@ -48,11 +48,27 @@ When the walk follows an existing table entry, `index_of` converts the address i `map_page` remembers every link it creates on the way down. If the walk fails, for example because the pool runs out or the leaf entry is already in use, it clears those links and restores the counter. The pool ends up exactly as it was before the call. -This matters after boot. Each `RETYPE` system call maps the new object into the kernel alias through this pool. Without the rollback, a user task could issue retypes that fail halfway and drain the pool a few tables at a time, until the kernel itself could no longer map anything. With the rollback, a failed retype costs nothing. Two host tests show this: +This matters after boot. Each `RETYPE` system call maps the new object into the kernel alias, and the rollback covers the tables taken from the reserve as well as those from the static array. Without the rollback, a user task could issue retypes that fail halfway and drain the tables a few at a time, until the kernel itself could no longer map anything. With the rollback, a failed retype costs nothing. Two host tests show this: - One fails a walk midway and checks that the pool is unchanged. - The other fails a thousand times in a row on a nearly full pool. +## The table reserve + +The tables for the kernel alias of retyped objects do not come from the static pool. At boot, for every memory range that becomes an `Untyped` capability, the kernel works out the largest number of tables that mapping every granule of the range can need, and sets that many granules aside inside the range. + +- `alias_tables_for` returns the bound for a range. It counts, for each of the three levels below the root, the blocks that the range touches, so the true need is never above it. +- The kernel takes this share from the top of the range and registers it with `reserve_tables`. The rest of the range, below the share, is what is handed out as `Untyped`. The share also holds the address space registry entries (see [user-address-space.md](user-address-space.md)). +- A reserve maps itself in pieces of one last-level table each, and registers every piece as soon as it is mapped. Only the first piece is paid for from what exists at that moment (the static pool or an earlier reserve). The rest of the range pays for itself. +- Table numbers continue from the static array into the reserves, in the order in which the reserves were registered. `index_of` accepts a table address only for a table that has already been handed out, in the array or in a reserve. +- A table from a reserve is **zeroed when it is handed out**, not at boot. +- If a walk fails, the rollback gives back the tables from both places. + +After boot, `alias_object` takes its tables from the reserves. It cannot fail for lack of tables for any address inside an `Untyped` that the kernel handed out. A range that cannot host its share, or whose share cannot be mapped, is **not handed out** as `Untyped`. The kernel prints `k0: memory + not handed out ()` and goes on booting. A gap that holds no whole granule is handed out unchanged, because no object can be made from it. + +> [!NOTE] +> The reserve costs one table per 2 MiB of memory with the 4 KiB granule (about 0.2 % of RAM), and one per 32 MiB with the 16 KiB granule (about 0.05 %). + ## Permissions > [!IMPORTANT] @@ -136,12 +152,13 @@ Any mismatch **stops the boot** with the name of the check. These checks test th ## How it is tested - `tools/boot-matrix.sh` boots the default build and the 16 KiB build on several QEMU configurations, and checks that unsupported configurations are refused with a reason in the boot log. -- Host unit tests in `crates/k0-mm/src/paging/tests.rs` check the index arithmetic for both granules, the W^X properties of every kernel permission, the rollback after a failed walk, the rejection of forged or block entries, and that an identical leaf is accepted only when the caller asks for it (`an_identical_leaf_is_accepted_only_when_asked`). They run on AArch64 hosts. +- Host unit tests in `crates/k0-mm/src/paging/tests.rs` check the index arithmetic for both granules, the W^X properties of every kernel permission, the rollback after a failed walk (also for tables from a reserve), the rejection of forged or block entries, the zeroing of reserve tables when they are handed out, the numbering across several reserves, and a reserve that cannot map its first piece (it is not registered), and that an identical leaf is accepted only when the caller asks for it (`an_identical_leaf_is_accepted_only_when_asked`). They run on AArch64 hosts. +- A host property test (`aliasing_every_granule_of_any_ranges_stays_within_the_bound`) draws random ranges near block boundaries, closes the static array, maps every granule of every range, and checks that no more tables are used than `alias_tables_for` gives. +- The root task self-test `test_reserve` retypes frames across up to 40 table blocks and requires that no `RETYPE` fails with `KERNEL_RESOURCE`. The marker `root: kernel reserve tests pass` and the boot line `k0: kernel reserve ` are required. - `tools/qemu-boot-test.sh` requires the line `k0: w^x checks pass`. ## Known gaps -- **Pool exhaustion**: the pool size is fixed at 40 tables. If retypes spread over enough distinct address ranges, the pool runs out and `RETYPE` returns `KERNEL_RESOURCE`. Nothing leaks, but the pool is never reclaimed. -- **Aliases stay**: kernel alias mappings are never removed. A retyped object stays mapped in the kernel alias even after its capability is revoked and its memory is retyped again. Reuse no longer fails, because an identical alias is accepted, but the alias itself and the tables that hold it stay. -- **Availability limit**: because of the previous two points, a task that holds a lot of untyped memory can retype across enough distinct address ranges to use up the pool. `RETYPE` then returns `KERNEL_RESOURCE` for every task, not only for the one that caused it. Isolation between tasks does not cover this availability limit. +- **Aliases stay**: kernel alias mappings are never removed. A retyped object stays mapped in the kernel alias even after its capability is revoked and its memory is retyped again. Reuse does not fail, because an identical alias is accepted, but the alias itself and the tables that hold it stay. The reserve is sized for this: it covers every granule of every handed-out range once. +- **Availability**: the kernel tables can no longer be used up by retyping, but availability in general is still not protected. The scheduler has no priority and no CPU budget, and a long system call delays every other task. Isolation between tasks does not cover availability. - **No ASIDs**: address space identifiers (ASIDs) are not used. Every switch to a different user address space invalidates the whole TLB. diff --git a/design/en/scheduling.md b/design/en/scheduling.md index 1659d4c..063b9f9 100644 --- a/design/en/scheduling.md +++ b/design/en/scheduling.md @@ -31,6 +31,7 @@ A **task control block** (TCB) holds the following: - **Queue links**: `next` and `prev`, the links to its neighbours in whatever queue the task is in. - **Reply right**: the single-use reply right (`reply_to`) and its reverse link (`reply_from`), described in [ipc.md](ipc.md). - **IPC wait information**: `blocked_on`, the endpoint the task is queued at, and `ipc_badge`, the badge of the message it is waiting to send. +- **Timeout fields**: `deadline`, the tick at which the task's IPC wait ends, and `tnext` and `tprev`, the links of the timed waiter list (see [Timeouts](#timeouts)). - **Three embedded capability slots**: slot 1 holds the task's `CNode` capability and slot 2 its `AddrSpace` capability. Slot 0 is unused. The **embedded slots** are what bind a task to its capability space and its address space. System calls resolve slot numbers only in the CNode named by slot 1 (see [capabilities.md](capabilities.md)), and the task runs in the address space named by slot 2. Both are copies, that is children in the derivation list, of the capabilities given to `TCB_CONFIGURE`, and they are marked as bound to the task. When either one is removed, the task is torn down (see [Teardown](#teardown)). @@ -44,7 +45,7 @@ The kernel reaches a TCB only through its own alias, and it is never mapped at E The following figure shows the task states and the transitions between them. The meaning of each state is in the table after it.

- Inactive becomes Stopped through TCB_CONFIGURE and Ready through TCB_RESUME, round robin moves a task between Running and Ready, a task blocks in IPC and becomes Ready when released, and teardown makes it Dead from any state + Inactive becomes Stopped through TCB_CONFIGURE and Ready through TCB_RESUME, round robin moves a task between Running and Ready, a task blocks in IPC and becomes Ready when its partner releases it or its deadline passes, and teardown makes it Dead from any state

| State | Meaning | @@ -57,6 +58,8 @@ The following figure shows the task states and the transitions between them. The | `BlockedReply` | waiting for the answer to a `CALL` | | `Dead` | exited, killed, or torn down | +A task in any of the blocked states can also become `Ready` when its deadline passes (see [Timeouts](#timeouts)). + `Inactive` has the value 0. A freshly retyped frame is all zeroes, so it already is a valid `Inactive` TCB with empty queue links, empty embedded slots and no reply right. Retype needs no constructor. ## Creating a task @@ -99,7 +102,7 @@ Three operations use this switch, as shown in the following table. | Operation | Used by | What happens to the current task | | --- | --- | --- | | `rotate` | `YIELD`, timer preemption | goes to the tail of the ready queue, unless nothing else is ready, in which case it simply continues | -| `block_and_switch` | IPC, and the system call exit path when the current task died | stays out of the ready queue. The caller has already put it in an endpoint queue or behind a reply right, or it is `Dead`. | +| `block_and_switch` | IPC, the idle loop, and the system call exit path when the current task died | stays out of the ready queue. The caller has already put it in an endpoint queue or behind a reply right, or it is `Dead`. | | `handoff` | boot, once | the root task becomes the first `Running` task | ## Preemption @@ -111,6 +114,15 @@ The timer fires once per second. When it fires while EL0 is running, the IRQ pat A timer interrupt that arrives at EL1 is possible only during boot, before the handoff, and it only counts the tick. +## Timeouts + +The tick is the unit of every IPC timeout, as described in [ipc.md](ipc.md). The scheduler keeps the waiters that have a deadline in a timed list (`arm_timeout`, `disarm_timeout`, `expired`, `has_timed` in `k0-sched`). The list is unsorted, and a lower bound of the earliest deadline lets most ticks skip it. + +A task leaves a blocked state only through `k0_sched::enqueue` (wake-up) or `k0_ipc::teardown` (death), and both remove it from the timed list. On every timer tick, `k0_ipc::expire_timeouts` wakes the waiters whose deadline has passed. It runs from `k0_preempt` when a task was running, and from the idle loop when none was. A timeout of n ticks ends at the (n+1)-th tick after the call. + +> [!NOTE] +> A timeout says when a task becomes ready, not when it runs. The woken task joins the tail of the ready queue like any other. + ## Teardown Teardown makes a task `Dead` and removes every kernel pointer that refers to it. It runs in the following cases: @@ -131,8 +143,8 @@ The following table shows what teardown does in each state. | `Dead` | nothing, so it is safe to call twice | | `Inactive`, `Stopped` | nothing to unlink | | `Ready` | removes the task from the ready queue | -| `BlockedSend`, `BlockedRecv`, `BlockedCall` | removes the task from the endpoint queue named by `blocked_on` | -| `BlockedReply` | clears the reply right in the task that holds it (`reply_from`) | +| `BlockedSend`, `BlockedRecv`, `BlockedCall` | removes the task from the endpoint queue named by `blocked_on`, and from the timed list if it has a deadline | +| `BlockedReply` | clears the reply right in the task that holds it (`reply_from`), and removes the task from the timed list if it has a deadline | | `Running` | nothing is unlinked. See below. | For every state it then withdraws any reply right the task itself holds, so that the caller waiting for that reply wakes with `NO_REPLY` and does not stay blocked forever. Finally it sets the state to `Dead`, clears the queue links, `blocked_on`, `reply_from`, `ipc_badge` and `ttbr0_pa`, and, unless the task is `Running`, zeroes its saved registers. A queue or reply link that does not match what the state promises is a kernel invariant violation, and the kernel halts with `k0: FATAL ...` (see [exceptions.md](exceptions.md)). @@ -143,13 +155,21 @@ A dead task's frame is not freed by teardown. It stays a `Dead` TCB, and `TCB_CO ## When there is nothing left to run -- **The current task died**: if the current task died during a kernel entry and no task is ready, `finish` prints `k0: all tasks exited` and parks the core. -- **The current task blocked**: if the current task blocks in IPC and no task is ready, `block_and_switch` reports it, and the kernel prints `k0: all tasks blocked` and parks. No other event can wake a task today, because notification objects do not exist yet. +The kernel no longer parks the core when no task can run. If the current task blocked or died and no task is ready, `idle_until_ready` in `kernel/src/syscall.rs` takes over: + +1. It waits for the next interrupt (`k0_arch::irq::wait_for_interrupt`: `wfi` with IRQs masked, then a short unmask so that the EL1 vector takes the interrupt). +2. It wakes every IPC waiter whose deadline has passed. +3. It switches to a ready task if there is one, and otherwise waits again. + +Timer ticks keep being counted and handled while the kernel idles. The idle loop prints one of two lines, each at most once per boot: + +- `k0: idle (waiting for a timeout)`: at least one waiter has a deadline. +- `k0: all tasks stopped (none ready, no timeout pending)`: no waiter has a deadline. Nothing can wake a task in that state today, because there are no notification objects and no device interrupts for tasks, so the machine stays idle. > [!WARNING] -> The case where every task is blocked is advisory GHSA-q99x-2wrv-358p in [SECURITY.md](../../SECURITY.md). Task isolation does not change this: a confined task that is the last one to block can still park the whole system. Isolation protects confidentiality and integrity between tasks, not availability. +> Availability is still not protected. A task that waits without a timeout can wait forever if its partner never acts, and a confined task that is the last one to block can still leave the system with nothing to run (advisory GHSA-q99x-2wrv-358p in [SECURITY.md](../../SECURITY.md), updated at release time). Isolation protects confidentiality and integrity between tasks, not availability. -Parking is a `wfe` loop inside the kernel, which runs with interrupts masked. +An SError taken from EL0 still stops the whole machine, and so does a `k0_arch::fatal` or a kernel panic. ## How it is tested @@ -162,17 +182,18 @@ The scheduler and the system call paths read system registers, so they are teste - build confined tasks that have their own CNode and their own address space, and check that the root task's slot numbers mean nothing there, and - delete a task in each state (inactive, stopped, ready, blocked in send, receive and call, waiting for a reply, holding a reply right, and at the head, middle and tail of an endpoint queue), delete endpoints with tasks queued, kill a task by revoking its CNode or deleting its address space, and have a task delete its own TCB and revoke the untyped it was carved from. -`tools/qemu-boot-test.sh` requires the markers `root: child exit test pass`, `root: preempt test pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: revocation tests pass` and `root: sched tests pass`, followed by at least one more timer tick. It fails if the log contains `k0: all tasks`, `k0: FATAL` or `k0: PANIC`, so a premature "all tasks exited" fails the run. 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: preempt test pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: revocation tests pass` and `root: sched tests pass`, followed by at least one more timer tick. The markers also include `k0: idle (waiting for a timeout)` and `root: timeout tests pass`, which come from the timeout tests (see [ipc.md](ipc.md)). It fails if the log contains a line that starts with `k0: all tasks`, `k0: FATAL` or `k0: PANIC`, so a run in which the kernel ends up with nothing to run and no timeout pending fails. It also counts task fault lines exactly (see [exceptions.md](exceptions.md)), which catches a task that keeps running after its teardown. ## Known gaps > [!NOTE] -> Priorities, budgets, timeouts and an idle state do not exist yet. There is one core only. +> Priorities and CPU budgets do not exist yet. There is one core only. -- **Scheduling**: plain round robin with a fixed one-second slice. -- **Behaviour without an idle state**: when the root task has finished its self-tests it keeps calling `YIELD`, so the CPU does not sleep. When no task can run, the kernel parks instead of waiting for an event. -- **Availability**: if every task is blocked, the kernel parks the core, and a confined task can cause this by blocking last (GHSA-q99x-2wrv-358p). Task isolation does not cover availability. -- **Blocked tasks**: a blocked task wakes only when its IPC partner acts or when the endpoint is deleted. +- **Scheduling**: plain round robin with a fixed one-second slice. A task that holds untyped memory can create many tasks and dilute everybody's share. +- **Timeouts**: they say when a task becomes ready, not when it runs. They are opt-in per call, so a task that waits without one can wait forever. +- **Idle state**: it exists, but while the root task keeps calling `YIELD` after its self-tests, the CPU does not sleep. When no task is ready and no waiter has a deadline, the machine stays idle and nothing can wake a task. +- **Availability**: a task that blocks without a timeout, including a confined one, can stay blocked for good if its partner never acts (GHSA-q99x-2wrv-358p). The kernel is not preemptible, so a long system call such as `CAP_REVOKE` on an untyped with many objects delays every other task and every timeout. Task isolation does not cover availability. +- **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. diff --git a/design/en/uefi.md b/design/en/uefi.md index 0bed28c..b2290dd 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 221 tests on an ARM host (`k0-abi` 12, `k0-cap` 41, `k0-boot` 76, `k0-efi` 32, and `k0-mm` 30 for each of the two granules) and 161 on an x86-64 host, where the `k0-mm` tests are skipped. +- **Host test script**: `tools/host-test.sh` now runs 250 tests on an ARM host (`k0-abi` 14, `k0-cap` 42, `k0-boot` 76, `k0-efi` 32, and `k0-mm` 43 for each of the two granules) and 164 on an x86-64 host, 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/user-address-space.md b/design/en/user-address-space.md index 0653133..ecce229 100644 --- a/design/en/user-address-space.md +++ b/design/en/user-address-space.md @@ -84,7 +84,16 @@ The root task's address space is no longer the only one. `RETYPE` with `ADDR_SPA ### The registry -A static registry in `k0-mm` (`AddrSpaces`, `MAX_ADDR_SPACES` entries, index 0 never used) gives every live address space an id (`asid`) and a generation. The root task's address space is registered in `kernel_main`, the others by `sys_retype`. Free entries form a singly linked list inside the array, so registering and releasing take no search. Releasing bumps the generation. An entry whose generation can no longer be bumped is retired and never handed out again. If the registry is full, `RETYPE` of an `AddrSpace` fails. +The registry in `k0-mm` (`AddrSpaces`) is sized at boot. It has **one 8-byte entry for every granule of every range that is handed out as untyped memory**. An entry holds a generation counter and a "live" bit. The entries live in the same reserve at the top of the range as the kernel's page tables (see [memory.md](memory.md)) and are zeroed at boot. + +- The id of an address space (`asid`) is the number of the granule that holds its root table (`root_pa / GRANULE`), a `u64`. It is the same number in `Cap::AddrSpace` and in mapping records. +- Releasing an address space bumps the generation. An old `(asid, generation)` pair therefore never matches a new address space at the same granule. +- The root task's address space has its root table in the boot window, not in untyped memory. It uses one dedicated entry (`register_boot`), registered in `kernel_main`. The others are registered by `sys_retype`. +- An address space needs one granule for its root, so every address space that memory allows has an entry. **There is no limit on the number of address spaces other than memory**, and `RETYPE` of an `AddrSpace` cannot fail for lack of a free entry. +- A generation that can no longer be bumped saturates: the granule is retired and never again becomes the root of an address space. Other granules are not affected. + +> [!NOTE] +> The entries cost 8 bytes per granule, about 0.2 % of RAM with the 4 KiB granule and 0.05 % with the 16 KiB granule. The boot log line `k0: kernel reserve tables + address space entries = bytes in ranges` shows the totals. A `Frame` or `PageTable` capability remembers where it is mapped as a record of `(asid, generation, va, level)`. It never stores a pointer. If the address space is destroyed first, the record no longer resolves, and the kernel does not walk a root table whose memory may already be something else. @@ -98,7 +107,7 @@ User space maps into an address space with `MAP`. The kernel walks the tables th - Mapping a `Frame` capability with `user_map_frame` **creates one leaf entry**. If an intermediate table is missing on the way, the call fails with `MISSING_TABLE`. The leaf must be empty, or the call fails with `OVERLAP`. - Mapping a `PageTable` capability with `user_install_table` **links a table**. It walks down the path of the given address and links the table into the first empty level it finds. If the path is already complete down to the leaf level, the call fails with `OVERLAP`. -User space therefore pays for its own page tables with its own untyped memory, by retyping `PageTable` objects. The kernel's static table pool is never charged for user mappings. +User space therefore pays for its own page tables with its own untyped memory, by retyping `PageTable` objects. The kernel's own tables are never charged for user mappings. Further rules in `sys_map`: @@ -151,7 +160,7 @@ When the CPU has FEAT_PAN, the kernel runs with PAN set, so any EL1 access throu - the W^X properties of every user permission - the validation paths that must reject bad input before touching any table - the real walkers on host memory: top-down table installation (`tables_install_top_down_and_frames_need_the_full_path`), unmap that clears only the leaf of the very frame (`unmap_clears_only_the_leaf_that_maps_this_very_frame`), uninstall that cuts exactly one link (`uninstall_cuts_exactly_one_link_and_a_zeroed_table_carries_nothing`), a model test of random map and unmap sequences (`random_map_and_unmap_agree_with_a_model`), and full coverage of the 48-bit range - - the registry: distinct non-zero ids, rejected bad ids, stale generations (`a_stale_generation_never_resolves_again`), random register and release sequences and retirement of an exhausted generation + - the registry: every granule of a range can hold an address space at once (`every_granule_of_a_range_can_hold_an_address_space_at_once`), ids the registry does not cover are rejected (`registry_rejects_what_it_does_not_cover`), stale generations (`a_stale_generation_never_resolves_again`), random register and release sequences (`registry_survives_random_register_release_sequences`), retirement of an exhausted generation (`a_granule_whose_generation_is_exhausted_is_retired`), the dedicated entry of the root task (`the_root_task_address_space_has_its_own_entry`), and independent ranges with a bounded table of ranges (`ranges_are_independent_and_the_table_of_ranges_is_bounded`) - `tools/host-test.sh` runs `k0-mm` for both granules on AArch64 hosts only. - The root task self-tests exercise the run-time path. They cover the following: - mapping before a page table exists @@ -167,13 +176,13 @@ When the CPU has FEAT_PAN, the kernel runs with PAN set, so any EL1 access throu - a detached table that does not carry its old leaf to a new place - stale frame records after the table was detached - reading and writing through the new mappings + - 300 address spaces alive at once, which is more than the old registry could hold (`test_reserve`) - The isolation self-tests build confined tasks with their own CNode and address space (only image text and read-only data mapped) and check that a read of a root-only address faults at exactly that address, that writes to a read-only page, execution from a stack page and reads of a kernel address fault, and that a task dies when its address space is deleted. - `tools/qemu-boot-test.sh` requires, among others, `k0: user w^x checks pass`, `root: retype/map tests pass`, `root: isolation tests pass`, `root: teardown tests pass` and `root: revocation tests pass`, and an exact count of `k0: task fault` lines. ## Known gaps -- **Availability**: isolation does not cover availability. If every task is blocked, the kernel parks the core (see [SECURITY.md](../../SECURITY.md)), and a confined task can cause this by blocking last. -- **Registry and pool limits**: the registry holds at most `MAX_ADDR_SPACES` address spaces. The kernel alias of every retyped object uses a static pool of kernel page tables. A task holding a lot of untyped memory can exhaust that pool, and then `RETYPE` fails with `KERNEL_RESOURCE` for everyone. +- **Availability**: isolation does not cover availability. The kernel no longer halts when every task is blocked, and the registry and the kernel page tables can no longer be used up by a task (see [memory.md](memory.md) and [SECURITY.md](../../SECURITY.md)). A task that waits without a timeout can still wait forever, and there is no priority and no CPU budget. A task that holds untyped memory can create many address spaces and tasks and dilute the share of the others. - **New executable code**: no new executable code can be loaded after boot, by design (per-frame W^X). A confined task can only run code from the root task image. - **Hardware ASIDs**: there are no hardware ASIDs, so every `TTBR0` switch and every unmap flushes the whole TLB. This costs performance, not safety. - **Kernel alias**: every frame mapped into user space is also mapped read-write in the kernel alias, because the kernel zeroed it there during retype. diff --git a/design/kr/README.md b/design/kr/README.md index 22a966a..59528b8 100644 --- a/design/kr/README.md +++ b/design/kr/README.md @@ -16,8 +16,8 @@ | 노트 | 주제 | | --- | --- | | [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`, 케이퍼빌리티가 제거될 때 매핑을 정리하는 방법 | +| [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, 태스크 격리가 다루는 것과 다루지 않는 것 | | [dtb_KR.md](dtb_KR.md) | 적대적 입력으로서의 디바이스 트리: 파서가 읽는 것, 한계, 퍼징 방법 | | [uefi_KR.md](uefi_KR.md) | UEFI 로더: 커널 밖에 두는 이유, 실행 흐름, RAM으로 인정하지 않는 메모리, 디바이스 트리 재작성, 점프 전 자가 검사, QEMU로 테스트할 수 없는 것, 부팅해 본 환경 | diff --git a/design/kr/boot_KR.md b/design/kr/boot_KR.md index 3171fea..f57de57 100644 --- a/design/kr/boot_KR.md +++ b/design/kr/boot_KR.md @@ -106,9 +106,10 @@ $ cargo build -p k0-kernel --offline --no-default-features --features granule-16 | `k0: root task integrity ok (...)` | 내장 루트 태스크 이미지를 다시 해시하고 빌드 시점에 고정된 해시와 비교합니다. | | `k0: entropy ...`, `k0: pac=... bti=... pan=...` | PAC 키를 파생해 적재하고 키 워드를 부트 스택에서 지우며, PAN을 켜고, 카운터·디버그·PMU에 대한 EL0 접근을 끕니다. [hardening_KR.md](hardening_KR.md)를 참고하세요. | | `k0: irq on (timer 1s)` | `setup_irq`가 필요한 인터럽트 컨트롤러 페이지만 매핑합니다. GICv3는 리디스트리뷰터 프레임을 하나씩 들여다보며 부트 CPU의 프레임을 찾은 뒤, 그 프레임과 SGI 프레임만 매핑합니다. 드라이버는 GIC 식별 레지스터가 DTB의 설명과 맞는지 확인합니다. EL1 가상 타이머는 플랫폼 기술서의 인터럽트 번호로 설정합니다. IRQ와 SError의 마스크를 해제합니다. | -| `k0: kernel table pool N/40` | 2 MiB 부트 프레임 윈도우를 고르고 매핑한 뒤, 사용 중인 커널 페이지 테이블 수를 출력합니다(예: QEMU virt에서 `16/40`). | +| `k0: kernel table pool N/40` | 2 MiB 부트 프레임 윈도우를 고르고 매핑한 뒤, 사용 중인 커널 페이지 테이블 수를 출력합니다(예: QEMU virt에서 `16/40`). 40개짜리 정적 풀은 부트 중에만 사용합니다. | | `k0: root task loaded (entry ...)` | 루트 태스크를 윈도우의 프레임에 복사하고, 윈도우에 루트 TCB를 만들고, 주소 공간을 만듭니다. 커널은 사용자 루트 테이블의 물리 주소를 출력하지 않습니다. 이후 이 주소 공간을 주소 공간 등록부에 올립니다. [user-address-space_KR.md](user-address-space_KR.md)를 참고하세요. | -| `k0: untyped ...`, `k0: root cnode ready (N caps, N untyped, N image frames, N slots)` | 루트 CNode(윈도우 안의 오브젝트이며 슬롯은 `ROOT_CNODE_SLOTS` = 512개, 로그에도 그렇게 나옵니다)를 채웁니다. 슬롯 1은 루트 TCB, 2는 루트 주소 공간, 3은 콘솔, 4는 루트 CNode 자신이고, 이어서 비어 있는 물리 범위마다 untyped 케이퍼빌리티, 루트 태스크 이미지의 매핑된 그래뉼마다 Frame 케이퍼빌리티 하나(text는 R과 X, 읽기 전용 데이터는 R, 데이터는 R과 W)가 들어갑니다. 마지막으로 루트 태스크를 다른 태스크와 똑같이 자신의 CNode와 주소 공간에 묶습니다. 두 케이퍼빌리티의 복사본이 TCB에 들어갑니다. [capabilities_KR.md](capabilities_KR.md)를 참고하세요. | +| `k0: memory + not handed out ()`(일어날 때만), `k0: kernel reserve tables + address space entries = bytes in ranges` | `reserve_kernel_share`가 untyped 케이퍼빌리티가 만들어지기 전에 비어 있는 물리 범위마다 커널 몫을 떼어 냅니다("untyped 메모리에서 커널 몫 떼어 내기" 참고). 자기 몫을 담지 못하는 범위는 넘기지 않으며, 이때 커널은 첫 번째 종류의 줄에 이유를 출력합니다. 두 번째 줄은 한 번 출력됩니다. 예를 들어 512 MiB, 4 KiB 그래뉼의 QEMU virt에서는 `k0: kernel reserve 262 tables + 130130 address space entries = 0x206000 bytes in 3 ranges`입니다. | +| `k0: untyped ...`, `k0: root cnode ready (N caps, N untyped, N image frames, N slots)` | 루트 CNode(윈도우 안의 오브젝트이며 슬롯은 `ROOT_CNODE_SLOTS` = 512개, 로그에도 그렇게 나옵니다)를 채웁니다. 슬롯 1은 루트 TCB, 2는 루트 주소 공간, 3은 콘솔, 4는 루트 CNode 자신이고, 이어서 넘기기로 한 비어 있는 물리 범위마다 untyped 케이퍼빌리티, 루트 태스크 이미지의 매핑된 그래뉼마다 Frame 케이퍼빌리티 하나(text는 R과 X, 읽기 전용 데이터는 R, 데이터는 R과 W)가 들어갑니다. 마지막으로 루트 태스크를 다른 태스크와 똑같이 자신의 CNode와 주소 공간에 묶습니다. 두 케이퍼빌리티의 복사본이 TCB에 들어갑니다. [capabilities_KR.md](capabilities_KR.md)를 참고하세요. | | `k0: bootinfo page ready` | 케이퍼빌리티 목록을 읽기 전용 bootinfo 페이지에 기록합니다. 헤더와 슬롯마다 하나의 디스크립터이며, 이미지 Frame마다 VA, 크기, 권한이 들어갑니다. | | `k0: user w^x checks pass` | `TTBR0`가 사용자 테이블을 가리키고, identity 매핑은 사라졌으며, 사용자 매핑을 EL0와 EL1 양쪽에서 검사합니다. | | `k0: device pages [...] of 0x1000 bytes` | 커널이 매핑한 채로 두는 모든 디바이스 페이지입니다. 이 줄 뒤에 커널은 더 이상 디바이스를 매핑하지 않습니다. | @@ -126,6 +127,18 @@ $ cargo build -p k0-kernel --offline --no-default-features --features granule-16 - **윈도우의 내용**: 루트 태스크 이미지, 스택, 페이지 테이블, bootinfo 페이지, 루트 TCB, 루트 CNode가 들어갑니다. - **untyped 제외**: 윈도우는 untyped 케이퍼빌리티에서 제외되므로, 커널이 아직 사용하는 메모리를 루트 태스크가 retype하는 일은 없습니다. +### untyped 메모리에서 커널 몫 떼어 내기 + +`kernel/src/main.rs`의 `reserve_kernel_share`는 루트 태스크를 적재한 뒤, untyped 케이퍼빌리티를 만들기 전에 실행됩니다. 비어 있는 물리 범위마다 다음과 같이 동작합니다. + +- **몫**: 범위의 모든 그래뉼을 매핑하는 데 필요할 수 있는 페이지 테이블의 최대 개수(`k0_mm::alias_tables_for`)와, 범위의 그래뉼마다 8바이트 주소 공간 항목 하나를 담는 데 필요한 그래뉼 수를 계산합니다. +- **배치**: 그 몫을 범위의 윗부분에서 가져옵니다. 테이블은 테이블 예비분이 되고(`k0_mm::reserve_tables`), 항목은 그 범위의 주소 공간 등록부가 됩니다(`add_range`). 항목 영역은 커널 별칭 윈도우에 매핑하고 0으로 지웁니다. 예비분의 테이블은 부팅 때가 아니라 넘겨줄 때 0으로 지웁니다. +- **결과**: 몫을 뺀 나머지 범위가 `Untyped` 케이퍼빌리티 하나로 넘어갑니다. 부팅 후 `alias_object`는 이 예비분에서 테이블을 가져오므로 태스크가 이를 소진할 수 없습니다. +- **몫을 담지 못하는 범위**: 너무 작거나 몫을 매핑할 수 없는 범위는 `Untyped`로 넘기지 않습니다. 커널은 `k0: memory + not handed out ()`을 출력하고 계속합니다. 범위 버퍼에 들어가지 않는 범위도 같은 방식으로 건너뜁니다(`too many ranges`). +- **온전한 그래뉼이 없는 틈**: 오브젝트를 만들 수 없고 몫도 필요 없으므로 그대로 넘깁니다. + +이 단계는 **부팅을 거부하지 않습니다**. 최악의 경우 메모리가 넘겨지지 않고 로그 한 줄이 그 사실을 알립니다. 오버헤드는 4 KiB 그래뉼에서 RAM의 약 0.2 %, 16 KiB 그래뉼에서 약 0.05 %입니다. 루트 태스크의 주소 공간은 루트 테이블이 부트 윈도우에 있으며 전용 등록부 항목 하나를 사용합니다. + ### 이양 이후 `handoff`는 루트 태스크를 실행 중인 태스크로 기록하고, 벡터 코드가 루트 태스크의 저장된 컨텍스트를 가리키게 합니다. 이어서 `enter_user`가 모든 예외를 마스크(`DAIFSet`)하고, 커널 스택을 꼭대기로 되감은 뒤, 이후의 모든 복귀가 사용하는 것과 같은 경로로 EL0에 복귀합니다. **마스크를 먼저 하는 이유**는 이 경로가 `eret` 전에 `ELR_EL1`과 `SPSR_EL1`을 기록하기 때문입니다. 부트 경로는 이미 타이머를 언마스크했으므로, 그 사이에 인터럽트가 들어오면 두 레지스터가 EL1 값으로 덮입니다. 이때부터 커널 코드는 예외에 대한 응답으로만 실행됩니다. 시스템 콜, 폴트, 타이머 인터럽트가 그 예외입니다. 이 경로는 [exceptions_KR.md](exceptions_KR.md)에서 설명합니다. diff --git a/design/kr/capabilities_KR.md b/design/kr/capabilities_KR.md index 70c03c3..283593c 100644 --- a/design/kr/capabilities_KR.md +++ b/design/kr/capabilities_KR.md @@ -47,6 +47,7 @@ - 권한이 없는 종류에 붙은 권한 - 남는 비트 - 매핑되지 않은 케이퍼빌리티의 매핑 기록 +- 0이거나, 슬롯이 담을 수 있는 가장 큰 그래뉼 번호보다 큰 주소 공간 번호(`asid`) - 리스트에 아직 걸려 있는 빈 슬롯 > [!IMPORTANT] @@ -119,17 +120,19 @@ 이미지 `Frame` 케이퍼빌리티의 권한은 세그먼트로 정해집니다. 텍스트는 `R|X`(`W` 없음), 읽기 전용 데이터는 `R`, 데이터는 `R|W`(`X` 없음)입니다. `X`를 가진 프레임은 시스템 전체에서 이 텍스트 프레임뿐이며, 그 내용은 부팅 시 해시 검증을 통과한 이미지입니다. 루트 태스크 자신의 부트 매핑은 영구적이고 이 케이퍼빌리티로 표현되지 않습니다. -untyped 케이퍼빌리티는 디바이스 트리가 보고한 RAM의 모든 바이트에서 모든 예약 구간을 제외한 범위를 덮습니다. 커널이 넘기는 예약 구간은 다음과 같습니다. +untyped 케이퍼빌리티는 디바이스 트리가 보고한 RAM의 모든 바이트에서 모든 예약 구간과, 구간마다 커널이 가져가는 자기 몫(아래 참고)을 제외한 범위를 덮습니다. 커널이 빼는 예약 구간은 다음과 같습니다. - 커널 이미지 - DTB - 2 MiB 부트 프레임 윈도우 - DTB의 모든 펌웨어 예약 구간. memory reservation block과 `/reserved-memory`의 자식 노드 모두 해당 -예약 구간은 서로 겹칠 수 있고 어떤 순서로 들어와도 됩니다. 각 메모리 리전마다 커서가 예약 구간을 주소 순서로 따라 앞으로 이동하면서 구간 사이의 틈을 내보냅니다. 그래서 겹치는 예약은 자연스럽게 병합됩니다. +예약 구간은 서로 겹칠 수 있고 어떤 순서로 들어와도 됩니다. 루트 CNode를 채우기 전에 커널이 `check_regions`로 리전을 검사합니다. 이어서 각 메모리 리전마다 `for_each_gap`이 커서를 예약 구간을 따라 주소 순서로 앞으로 이동시키면서 구간 사이의 틈을 내보냅니다. 그래서 겹치는 예약은 자연스럽게 병합됩니다. + +커널은 각 틈의 맨 위에서 자기 몫을 가져갑니다. 커널 별칭용 페이지 테이블과 주소 공간 등록부 항목입니다([memory_KR.md](memory_KR.md)와 [user-address-space_KR.md](user-address-space_KR.md) 참고). `bootstrap`은 남은 구간을 이미 잘라 낸 상태로 받아 구간마다 `Untyped` 케이퍼빌리티 하나를 만듭니다. 자기 몫을 둘 수 없는 틈은 넘기지 않으며, 커널은 `k0: memory + not handed out ()`를 출력합니다. > [!IMPORTANT] -> 메모리 리전끼리는 겹쳐서는 안 됩니다. 두 리전이 겹치면 같은 물리 프레임이 두 untyped 케이퍼빌리티에 들어가 서로 다른 오브젝트 두 개로 retype될 수 있습니다. `bootstrap`은 이런 맵을 거부하고, 커널은 부팅을 중단합니다. +> 메모리 리전끼리는 겹쳐서는 안 됩니다. 두 리전이 겹치면 같은 물리 프레임이 두 untyped 케이퍼빌리티에 들어가 서로 다른 오브젝트 두 개로 retype될 수 있습니다. `check_regions`는 이런 맵을 거부하고, 커널은 부팅을 중단합니다. 슬롯이 부족한 경우에도 부팅이 중단됩니다. CPU의 물리 주소 폭을 넘는 DTB 메모리 리전을 만나도 부팅이 중단됩니다. @@ -162,11 +165,11 @@ untyped 케이퍼빌리티는 디바이스 트리가 보고한 RAM의 모든 바 5. untyped에 자손이 없으면 워터마크를 베이스로 되돌립니다(뒤의 "메모리 재사용" 절 참고). 6. 올림한 워터마크에 1 그래뉼을 더한 값이 untyped 범위 안에 들어와야 하고(모든 덧셈은 오버플로를 검사), 오브젝트의 물리 주소가 슬롯에 인코딩될 수 있어야 합니다. 아니면 `EXHAUSTED`입니다. 7. 새 케이퍼빌리티의 파생 깊이가 `MAX_DEPTH` 안이어야 하며, 아니면 `TOO_DEEP`입니다. -8. 여기까지 통과한 뒤에야 커널이 메모리를 준비합니다. `sys_retype`의 콜백이 그래뉼을 커널 별칭에 매핑하고([memory_KR.md](memory_KR.md) 참고, 같은 별칭을 다시 매핑하는 것은 허용됩니다) 0으로 채웁니다. `ADDR_SPACE`이면 새 주소 공간을 등록부에도 등록합니다. 여기서 실패하면 `KERNEL_RESOURCE`입니다. +8. 여기까지 통과한 뒤에야 커널이 메모리를 준비합니다. `sys_retype`의 콜백이 그래뉼을 커널 별칭에 매핑하고([memory_KR.md](memory_KR.md) 참고, 같은 별칭을 다시 매핑하는 것은 허용됩니다) 0으로 채웁니다. `ADDR_SPACE`이면 새 주소 공간을 등록부에도 등록합니다. 테이블과 등록부 항목은 커널이 부팅 때 따로 떼어 둔 예약 구간에서 나오므로, 커널이 넘긴 `Untyped` 안의 그래뉼에는 항상 둘 다 있습니다. 여기서 실패하면 `KERNEL_RESOURCE`가 되지만, 알려진 원인은 남아 있지 않습니다. 9. 준비가 성공한 경우에만 워터마크를 옮기고 새 케이퍼빌리티를 목적지 슬롯에 넣습니다. > [!IMPORTANT] -> 어느 단계든 실패하면 아무것도 바뀌지 않습니다. 워터마크, 목적지 슬롯, 등록부, 커널 테이블 풀이 모두 이전 그대로이고, 호출자는 에러 코드를 받습니다. 메모리는 케이퍼빌리티가 생기기 전에 0으로 채워지므로, 어떤 태스크도 retype된 메모리의 이전 내용을 볼 수 없습니다. +> 어느 단계든 실패하면 아무것도 바뀌지 않습니다. 워터마크, 목적지 슬롯, 등록부, 커널 테이블이 모두 이전 그대로이고, 호출자는 에러 코드를 받습니다. 메모리는 케이퍼빌리티가 생기기 전에 0으로 채워지므로, 어떤 태스크도 retype된 메모리의 이전 내용을 볼 수 없습니다. 0으로 채우는 것은 보안 단계이면서 동시에 설계상의 선택입니다. 메모리의 이전 내용이 새 오브젝트로 새어 나가는 것을 막고, 0으로 채운 프레임이 그 자체로 유효한 초기 오브젝트가 되게 합니다. 0으로 채운 오브젝트는 다음과 같이 해석됩니다. @@ -232,7 +235,7 @@ untyped를 회수하면 거기서 잘라낸 것이 전부 종료됩니다. 조 - **Tcb**(원본), 그리고 태스크에 묶인 모든 케이퍼빌리티: 그 태스크를 종료시킵니다. [scheduling_KR.md](scheduling_KR.md)와 [ipc_KR.md](ipc_KR.md)를 참고하세요. - **AddrSpace**(원본): 등록부에서 해제하고(이때 세대가 올라갑니다), TTBR0에 설치돼 있으면 TTBR0를 커널 풀의 빈 테이블로 바꿉니다. -**매핑 기록**은 `(id, 세대, va, 레벨)`입니다. 해제, 삭제, 회수는 등록부가 여전히 같은 주소 공간이라고 확인한 루트만 걷고, 정확히 그 프레임이나 테이블을 가리키는 엔트리만 지웁니다. [user-address-space_KR.md](user-address-space_KR.md)를 참고하세요. +**매핑 기록**은 `(asid, 세대, va, 레벨)`입니다. `asid`는 주소 공간의 루트 테이블이 놓인 그래뉼의 번호이고 `u64`입니다(`Cap::AddrSpace`의 번호와 같음). 워드를 해석할 때 검사합니다. 해제, 삭제, 회수는 등록부가 여전히 같은 주소 공간이라고 확인한 루트만 걷고, 정확히 그 프레임이나 테이블을 가리키는 엔트리만 지웁니다. [user-address-space_KR.md](user-address-space_KR.md)를 참고하세요. **재귀를 사용하지 않습니다**. CNode와 TCB는 슬롯을 담고 있으므로, 이를 종료시키면 담고 있던 것을 삭제해야 하고 그것이 또 다른 컨테이너를 종료시킬 수 있습니다. k0-cap은 재귀하지 않습니다. 종료된 컨테이너의 슬롯 배열을 그 배열의 0번 슬롯으로 엮은 보류 목록에 걸어 두었다가, 같은 호출 안에서 반복문으로 비웁니다. 커널 스택 사용량은 파생 깊이나 CNode 중첩과 무관하게 일정합니다. 시간은 제거되는 케이퍼빌리티 수에 비례하며, 그동안 인터럽트는 마스크된 상태입니다. @@ -278,7 +281,7 @@ untyped를 회수하면 거기서 잘라낸 것이 전부 종료됩니다. 조 | `BAD_BADGE` | 배지를 가질 수 없는 종류에 배지를 요구했거나, 이미 배지가 있는 케이퍼빌리티에 다른 배지를 요구함 | | `TOO_DEEP` | 파생 깊이 상한을 넘게 됨 | | `REVOKED` | 대기 중이던 엔드포인트가 삭제되어 깨어난 태스크가 받음 | -| `KERNEL_RESOURCE` | 커널 내부 풀 고갈(별칭 매핑용 커널 테이블 풀, 주소 공간 등록부) | +| `KERNEL_RESOURCE` | 커널 내부 자원 부족. 여전히 정의된 코드이지만, 커널 별칭 테이블과 주소 공간 등록부는 더 이상 원인이 될 수 없음 | ## 테스트 방법 @@ -325,9 +328,9 @@ untyped를 회수하면 거기서 잘라낸 것이 전부 종료됩니다. 조 ## 알려진 공백 > [!NOTE] -> 케이퍼빌리티 전송은 아직 없습니다. IPC로 케이퍼빌리티를 보낼 수 없고, 태스크가 케이퍼빌리티를 얻는 방법은 이미 가진 CNode 안으로 하는 `CAP_COPY`와 `CAP_MOVE`뿐입니다. 알림(notification), 핸들러 태스크로의 폴트 전달, 타임아웃도 아직 모델에 없고 코어는 하나입니다. +> 케이퍼빌리티 전송은 아직 없습니다. IPC로 케이퍼빌리티를 보낼 수 없고, 태스크가 케이퍼빌리티를 얻는 방법은 이미 가진 CNode 안으로 하는 `CAP_COPY`와 `CAP_MOVE`뿐입니다. 알림(notification)과 핸들러 태스크로의 폴트 전달도 아직 모델에 없고 코어는 하나입니다. 타임아웃은 있습니다([ipc_KR.md](ipc_KR.md) 참고). -- **가용성**: 격리되지 않습니다. 모든 태스크가 블록되면 커널은 여전히 코어를 파킹하며([SECURITY_KR.md](../../SECURITY_KR.md)의 GHSA-q99x-2wrv-358p 참고), 격리된 태스크가 마지막으로 블록되어 이를 일으킬 수 있습니다. untyped 메모리를 많이 가진 태스크는 별칭 매핑에 사용하는 정적 커널 페이지 테이블 풀(40개)이나 주소 공간 등록부를 고갈시킬 수 있습니다. 그러면 `RETYPE`이 모두에게 `KERNEL_RESOURCE`로 실패합니다. +- **가용성**: 격리되지 않습니다. 모든 태스크가 블록되어도 커널은 더 이상 멈추지 않고, 태스크는 타임아웃으로 자기 대기를 제한할 수 있으며, 커널 페이지 테이블과 주소 공간 등록부는 더 이상 소진될 수 없습니다. 타임아웃 없이 기다리는 태스크는 상대가 움직이지 않으면 여전히 영원히 기다릴 수 있으므로, 서버는 모든 대기에 타임아웃을 주어야 합니다. 우선순위와 CPU 예산은 없고, untyped 메모리를 가진 태스크는 태스크를 많이 만들어 다른 태스크의 몫을 희석시킬 수 있습니다. 커널은 선점되지 않으므로 `CAP_REVOKE` 같은 긴 시스템 콜은 모두를 지연시킵니다. 어드바이저리의 상태는 [SECURITY_KR.md](../../SECURITY_KR.md)의 GHSA-q99x-2wrv-358p를 참고하세요. - **줄 서 있던 송신자**: 엔드포인트에 이미 줄 서 있던 송신자는 자기 케이퍼빌리티가 회수된 뒤에도 메시지를 한 번 더 전달합니다. - **seL4와의 차이**: 다음과 같습니다. - 단일 레벨 CSpace입니다(가드나 다단계 조회 없음). diff --git a/design/kr/exceptions_KR.md b/design/kr/exceptions_KR.md index b8b0554..0bb183a 100644 --- a/design/kr/exceptions_KR.md +++ b/design/kr/exceptions_KR.md @@ -43,7 +43,9 @@ fatal 엔트리는 **스택 포인터를 신뢰하지 않습니다**. 폴트가 ### 커널 안에서 발생한 인터럽트 -EL1에서 받은 IRQ는 caller-saved 레지스터를 커널 스택에 저장하고, 핸들러를 호출한 뒤 복귀합니다. 이양 이후에는 이 경로가 발생하지 않습니다. 예외 진입이 인터럽트를 마스크하고, 커널이 예외를 처리하는 동안 마스크를 해제하지 않기 때문입니다. 커널 자체는 선점되지 않습니다. +EL1에서 받은 IRQ는 caller-saved 레지스터를 커널 스택에 저장하고, 핸들러를 호출한 뒤 복귀합니다. 커널은 예외를 처리하는 동안 인터럽트를 마스크한 채로 둡니다. 예외는 `idle_until_ready`의 대기([종료 경로](#종료-경로) 참고) 하나뿐입니다. 커널 자체는 선점되지 않습니다. + +대기 중에는 `k0_arch::irq::wait_for_interrupt`가 대기 중인 인터럽트 하나를 위해 I 비트만 엽니다(IRQ를 마스크한 채 `wfi`를 실행하고, 이어서 짧게 마스크를 해제함). 이것이 안전한 이유는 세 가지입니다. 첫째, ELR_EL1과 SPSR_EL1을 포함한 EL0 컨텍스트 전체가 이미 TCB에 저장되어 있으므로, 중첩된 EL1 IRQ가 두 레지스터를 덮어써도 잃는 것이 없습니다. 둘째, 핸들러는 커널 스택에서 실행되며, 예외 진입이 스택 최상단에서 시작하므로 여유가 충분합니다. 셋째, 인터럽트를 받은 직후 마스크를 다시 설정하므로 다른 커널 코드는 인터럽트가 열린 채 실행되지 않습니다. ### EL2의 벡터 @@ -120,16 +122,25 @@ k0: task fault dabort-lower (esr 0x92000046 elr 0x400398 far 0x0), killing task 모든 시스템 콜과 모든 폴트는 `finish`로 끝납니다. `finish`는 핸들러가 끝나고 케이퍼빌리티 정리가 전부 끝난 뒤에 실행됩니다. 핸들러는 폴트 없이도 호출한 태스크를 죽일 수 있습니다. `EXIT`, 자신의 CNode·주소 공간·TCB 삭제, 자신이 잘려 나온 untyped의 회수가 그렇습니다. 그래서 `finish`는 다른 모든 일이 끝난 뒤에야 컨텍스트를 어떻게 할지 정합니다. -1. **현재 태스크가 Dead인 경우**: 그 컨텍스트에 반환값을 기록하지 않습니다. 컨텍스트를 0으로 지우므로 죽은 태스크의 레지스터는 하나도 남지 않고, 커널은 다음 준비 태스크로 전환합니다. 준비된 태스크가 없으면 `k0: all tasks exited`를 출력하고 파킹합니다. +1. **현재 태스크가 Dead인 경우**: 그 컨텍스트에 반환값을 기록하지 않습니다. 컨텍스트를 0으로 지우므로 죽은 태스크의 레지스터는 하나도 남지 않고, 커널은 다음 준비 태스크로 전환합니다. 준비된 태스크가 없으면 `idle_until_ready`를 호출합니다(아래 참고). 2. **그 밖의 경우**: 반환값을 `x0`에 기록합니다. 블록하는 IPC 호출은 상대가 동작할 때 나중에 결과를 기록합니다. 정리가 전환보다 먼저인 이유는, revoke가 태스크가 사용하던 주소 공간이나 CNode 자체를 파괴할 수 있기 때문입니다. 다음 태스크가 끝나지 않은 정리 위에서 실행되어서는 안 됩니다. +준비된 태스크가 없으면(마지막 실행 가능 태스크가 죽었거나 모든 태스크가 블록된 경우) `idle_until_ready`가 **커널을 멈추지 않고 대기 상태로 둡니다**. 루프에서 `k0_arch::irq::wait_for_interrupt`로 다음 인터럽트를 기다리고, `k0_ipc::expire_timeouts`를 호출해 기한이 지난 IPC 대기자를 모두 깨우고, 준비된 태스크가 있으면 그쪽으로 전환합니다. 커널이 대기하는 동안에도 타이머 tick은 계속 세어지고 처리됩니다. 중첩된 EL1 IRQ는 [커널 안에서 발생한 인터럽트](#커널-안에서-발생한-인터럽트)에서 설명합니다. 이 함수는 다음 두 줄을 부팅당 최대 한 번씩 출력합니다. + +| 줄 | 시점 | +| --- | --- | +| `k0: idle (waiting for a timeout)` | 기한을 가진 대기자가 하나 이상 있는 채로 커널이 처음 대기할 때 | +| `k0: all tasks stopped (none ready, no timeout pending)` | 기한을 가진 대기자가 없는 채로 커널이 처음 대기할 때 | + +두 번째 상태에서는 지금으로서는 태스크를 깨울 수단이 없습니다. 알림 오브젝트도, 태스크용 장치 인터럽트도 없기 때문입니다. 기계는 대기 상태로 남습니다. `tools/qemu-boot-test.sh`는 `k0: all tasks`로 시작하는 줄이 나오면 실패로 판정합니다. + ## EL0의 타이머 인터럽트 커널이 켜는 인터럽트는 **EL1 가상 타이머 하나뿐**입니다. 인터럽트 번호는 DTB에서 가져오며, 커널은 물리 타이머를 사용하지 않습니다. 인터럽트 컨트롤러는 DTB가 타이머의 인터럽트 부모로 가리키는 GICv2 또는 GICv3입니다. 드라이버는 레지스터에 기록하기 전에 식별 레지스터를 그 기술과 대조하고, 다르면 부팅을 거부합니다. [dtb_KR.md](dtb_KR.md)를 참고하세요. -EL0에서 받은 IRQ는 시스템 콜과 같은 방식으로 저장됩니다. 핸들러는 인터럽트를 확인합니다. 타이머였다면 타이머를 1초 뒤로 다시 설정하고 `k0: tick N`을 출력합니다. 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔에 출력하며, 로그에는 처음 4개의 tick 줄만 남깁니다. 그다음 `k0_preempt`를 호출하며, 이 함수가 다음 준비 태스크로 순환합니다. 1020부터 1023까지의 가짜 인터럽트 번호는 무시합니다. 그 외의 인터럽트 번호와 모든 FIQ는 설계상 발생할 수 없으므로 커널은 `k0: UNEXPECTED ...`를 출력하고 파킹합니다. +EL0에서 받은 IRQ는 시스템 콜과 같은 방식으로 저장됩니다. 핸들러는 인터럽트를 확인합니다. 타이머였다면 타이머를 1초 뒤로 다시 설정하고 `k0: tick N`을 출력합니다. 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔에 출력하며, 로그에는 처음 4개의 tick 줄만 남깁니다. 그다음 `k0_preempt`를 호출합니다. 이 함수는 먼저 기한이 된 IPC 타임아웃을 만료시키고(`k0_ipc::expire_timeouts`), 그래서 기한이 지난 대기자는 라운드 로빈 전환 전에 준비 상태가 됩니다. 그런 다음 다음 준비 태스크로 순환합니다. 1020부터 1023까지의 가짜 인터럽트 번호는 무시합니다. 그 외의 인터럽트 번호와 모든 FIQ는 설계상 발생할 수 없으므로 커널은 `k0: UNEXPECTED ...`를 출력하고 파킹합니다. ## 테스트 방법 @@ -145,5 +156,6 @@ EL0에서 받은 IRQ는 시스템 콜과 같은 방식으로 저장됩니다. > 폴트를 일으킨 태스크는 항상 종료됩니다. 페이저나 감독자가 대응할 수 있도록 폴트를 IPC로 핸들러 태스크에 전달하는 기능은 계획되어 있지만 아직 없습니다. - 인터럽트를 제외한 **EL1의 모든 예외는 치명적**입니다. 커널은 자신의 폴트를 복구하지 않습니다. fatal 벡터 경로가 진단을 출력하고 시스템 전체를 정지시킵니다. 커널 자신의 검사가 찾아낸 불변식 위반도 `k0_arch::fatal`을 거쳐 같은 방식으로 정지합니다. -- 폴트를 일으키거나 알 수 없는 시스템 콜을 호출한 태스크는 자기만 죽지만, 마지막 실행 가능 태스크였다면 **시스템 전체가 파킹**됩니다(`k0: all tasks exited`). 모든 태스크가 블록되어도 커널은 파킹합니다(GHSA-q99x-2wrv-358p). 격리는 가용성을 다루지 않습니다. +- 폴트를 일으키거나 알 수 없는 시스템 콜을 호출한 태스크는 자기만 죽습니다. 그 뒤 준비된 태스크가 없으면 커널은 멈추지 않고 대기합니다([종료 경로](#종료-경로) 참고). 타임아웃 없이 기다리는 태스크는 상대가 동작하지 않으면 계속 기다릴 수 있고, 스케줄러에는 우선순위도 CPU 예산도 없습니다(GHSA-q99x-2wrv-358p는 여전히 0.1.0 이하에 영향을 주는 것으로 게시되어 있음). 격리는 가용성을 다루지 않습니다. +- 다음 경우에는 시스템 전체가 여전히 정지합니다. `k0_arch::fatal`과 fatal 벡터 경로, 커널 패닉, EL0에서 받은 SError, EL2로의 트랩입니다. - 폴트 메시지에는 **사용자 주소가 포함**됩니다. 디버깅에는 유용하지만, 부트 로그와 (콘솔 드라이버를 포함해 빌드한 이미지에서는) 콘솔로 출력됩니다. `Console` 케이퍼빌리티를 가진 모든 태스크가 그 둘에 기록할 수 있습니다. diff --git a/design/kr/hardening_KR.md b/design/kr/hardening_KR.md index 7b590b3..077037f 100644 --- a/design/kr/hardening_KR.md +++ b/design/kr/hardening_KR.md @@ -80,6 +80,8 @@ CPU가 FEAT_E0PD를 구현하면 `TCR_EL1.E0PD1`을 설정합니다. 그러면 E EL0의 트랩은 폴트로 처리되고 태스크는 종료됩니다([exceptions_KR.md](exceptions_KR.md) 참고). 유일한 예외는 `WFI`와 `WFE`로, 커널이 건너뜁니다. FP/SIMD를 트랩하면 커널이 벡터 레지스터를 저장할 필요가 전혀 없으므로, 태스크는 다른 태스크가 남긴 벡터 상태를 읽을 수 없습니다. +EL0는 여전히 어떤 하드웨어 카운터나 타이머도 읽을 수 없습니다. 다만 IPC 타임아웃은 EL0에 **스케줄러 tick만큼 거친 시계**(1초)와 타이머 인터럽트에 맞춰 정렬된 깨어남을 제공합니다([ipc_KR.md](ipc_KR.md) 참고). 따라서 **tick 주기는 사이드 채널에 관한 결정**입니다. 이 시계가 캐시나 추측 실행 공격에 쓸 만한 시간 원천으로 증폭될 수 있는지는 분석하지 않았습니다. + EL0 스레드 포인터 레지스터 `TPIDR_EL0`와 `TPIDRRO_EL0`는 각 태스크의 저장된 컨텍스트에 포함됩니다. `TCB_CONFIGURE`가 이를 0으로 만들기 때문에 새 태스크는 생성자의 값 없이 시작합니다. `DEBUG_PUTC`는 `Console` 케이퍼빌리티를 요구하며, 출력 가능한 ASCII도 개행도 아닌 모든 바이트를 `?`로 바꿉니다. 태스크는 콘솔을 읽는 쪽에 터미널 이스케이프 시퀀스를 보낼 수 없습니다(콘솔 드라이버를 포함해 빌드한 이미지의 콘솔, 또는 부트 로그). diff --git a/design/kr/ipc_KR.md b/design/kr/ipc_KR.md index 3c72121..708b0c3 100644 --- a/design/kr/ipc_KR.md +++ b/design/kr/ipc_KR.md @@ -53,7 +53,15 @@ K0의 IPC는 seL4 방식의 **동기 랑데부**입니다. 메시지는 레지 ## 네 가지 호출 -네 호출 모두 `x0`에 `Endpoint` 케이퍼빌리티를, `x1`에 플래그를 받습니다. 플래그는 `NONBLOCK` 하나뿐이며, 상대방이 준비되지 않았을 때 기다리지 않고 `WOULD_BLOCK`을 반환합니다. 타임아웃이 없으므로 `NONBLOCK`이 기다리지 않는 유일한 방법입니다. 다음 그림은 서버가 먼저 `RECV`로 기다리는 경우에 `CALL`과 `REPLY_RECV`가 오가는 순서를 보여 줍니다. +네 호출 모두 `x0`에 `Endpoint` 케이퍼빌리티를, `x1`에 플래그를 받습니다. 플래그 레지스터의 구성은 다음과 같습니다. + +| 비트 | 이름 | 의미 | +| --- | --- | --- | +| 0 | `NONBLOCK` | 상대방이 준비되지 않았을 때 기다리지 않고 `WOULD_BLOCK`을 반환 | +| 31부터 1 | 예약(`k0_abi::ipc::RESERVED`) | 반드시 0 | +| 63부터 32 | 타임아웃 | 스케줄러 틱 단위의 최대 대기 시간, 0은 영원히 기다림([타임아웃](#타임아웃) 참고) | + +`k0_abi::ipc::timeout(ticks)`가 타임아웃 값을 만들고, `k0_abi::ipc::TIMEOUT_SHIFT`는 32입니다. `NONBLOCK`이 타임아웃보다 우선합니다. 예약 비트가 하나라도 서 있는 호출은 다른 어떤 것도 보기 전에 `BAD_FLAGS`로 실패합니다. `REPLY_RECV`의 경우에는 대기 중인 응답을 소모하기 전에 실패합니다. 다음 그림은 서버가 먼저 `RECV`로 기다리는 경우에 `CALL`과 `REPLY_RECV`가 오가는 순서를 보여 줍니다.

서버가 RECV로 기다리는 경우, 클라이언트의 CALL은 메시지와 배지를 서버에 전달하고 클라이언트를 BlockedReply로 블록하며, 서버의 REPLY_RECV는 1회성 응답 자격으로 클라이언트를 깨우는 순서 @@ -67,7 +75,7 @@ K0의 IPC는 seL4 방식의 **동기 랑데부**입니다. 메시지는 레지 **CALL**은 메시지 송신과 응답 대기를 트랩 한 번에 수행합니다. 수신자가 기다리고 있다면 메시지가 전달되고 호출자는 곧바로 `BlockedReply`로 넘어갑니다. 그렇지 않으면 호출자는 `BlockedCall`로 큐에서 기다립니다. 어느 쪽이든 **호출자는 항상 블록됩니다**. 송신과 대기가 한 단계에서 일어나므로, 둘 사이의 틈에 응답이 도착하는 일은 있을 수 없습니다. -**REPLY_RECV**는 서버 루프를 트랩 한 번으로 수행합니다. 호출한 태스크가 응답 자격을 가지고 있으면 커널은 `x2`부터 `x5`를 대기 중인 호출자에 대한 응답으로 전달하고, 호출자를 준비 상태로 만들고, 응답 자격을 버립니다. 그다음에는 `RECV`와 똑같이 이어서 진행합니다. +**REPLY_RECV**는 서버 루프를 트랩 한 번으로 수행합니다. 호출한 태스크가 응답 자격을 가지고 있으면 커널은 `x2`부터 `x5`를 대기 중인 호출자에 대한 응답으로 전달하고, 호출자를 준비 상태로 만들고, 응답 자격을 버립니다. 그다음에는 `RECV`와 똑같이 이어서 진행하며, 타임아웃도 마찬가지로 이 수신 단계에만 적용됩니다. 엔드포인트를 먼저 검사합니다. 엔드포인트 케이퍼빌리티가 유효하지 않거나 `R`이 없으면 응답 자격을 소모하지 않고 호출이 실패합니다. 응답은 `x1 = 0`으로 전달됩니다. @@ -97,20 +105,61 @@ K0의 IPC는 seL4 방식의 **동기 랑데부**입니다. 메시지는 레지 - **응답 자격 보유**: 그 자격을 기다리던 호출자를 `NO_REPLY`로 깨웁니다. - **Inactive, Stopped, Running**: 풀 것이 없습니다. -그 뒤 상태는 `Dead`가 되고 저장된 레지스터는 소거됩니다. 시스템 콜을 호출한 태스크 자신이 죽었다면 커널은 그 태스크에 반환 값을 기록하지 않고 다음 준비 태스크로 전환합니다. +기한을 걸고 기다리던 태스크는 스케줄러의 기한 목록에서도 제거됩니다. 그 뒤 상태는 `Dead`가 되고 저장된 레지스터는 소거됩니다. 시스템 콜을 호출한 태스크 자신이 죽었다면 커널은 그 태스크에 반환 값을 기록하지 않고 다음 준비 태스크로 전환합니다. 엔드포인트의 원본 케이퍼빌리티가 삭제되면 그 엔드포인트에 줄 서 있던 태스크가 모두 `REVOKED`로 깨어나고, 이후 어떤 TCB도 그 엔드포인트를 가리키지 않습니다. 케이퍼빌리티의 복사본만 삭제하면 큐는 건드리지 않습니다. +## 타임아웃 + +모든 대기에 상한을 걸 수 있습니다. 타임아웃은 플래그 레지스터 `x1`의 상위 32비트이며 스케줄러 틱 단위입니다. 틱 주기는 1초(커널 상수)이므로 모든 타임아웃의 단위는 틱입니다. 다음 규칙이 적용됩니다. + +- **기한 규칙**: n 틱의 타임아웃은 호출 뒤 (n+1)번째 타이머 틱에서 끝납니다. 틱이 제때 처리되는 한 대기는 틱 주기의 n배에서 n+1배 사이입니다. +- **하한이지 벽시계 시간이 아님**: 커널은 모든 시스템 콜을 인터럽트를 마스크한 채 실행하고, 큰 `CAP_REVOKE`처럼 긴 호출은 틱을 늦춥니다. 그러면 대기도 그만큼 길어집니다. +- **0은 기한 없음**: 이전처럼 상대방이 동작할 때까지 기다립니다. +- **호출의 기한은 하나**: `CALL`의 기한은 수신자를 기다리는 단계와 응답을 기다리는 단계를 모두 덮습니다. +- **응답 후 수신**: `REPLY_RECV`의 타임아웃은 수신 단계에만 적용됩니다. + +다음 표는 타임아웃으로 대기가 끝났을 때 호출자가 받는 결과입니다. + +| 호출 | 기다린 곳 | 결과 | 메시지는 | +| --- | --- | --- | --- | +| `SEND` | 엔드포인트 큐 | `TIMEOUT` | 전달되지 않음 | +| `RECV`, `REPLY_RECV` | 엔드포인트 큐 | `TIMEOUT` | 받은 것 없음(`REPLY_RECV`가 준 응답은 이미 전달됨) | +| `CALL` | 엔드포인트 큐 | `TIMEOUT` | 전달되지 않음 | +| `CALL` | `BlockedReply` | `REPLY_TIMEOUT` | 전달됨, 서버가 동작했는지는 알 수 없음 | + +`CALL`이 `REPLY_TIMEOUT`으로 끝나면 커널은 그 응답 자격을 쥔 서버의 자격을 지웁니다. 서버가 나중에 응답해도 그 `REPLY_RECV`에는 사용할 응답 자격이 없으므로 뒤늦은 응답은 버려집니다. 다음 호출자는 자기 응답을 받습니다. + +### 기한 목록 + +TCB에는 `deadline`, `tnext`, `tprev` 필드가 있습니다. `k0-sched`는 기한이 있는 대기자의 정렬되지 않은 intrusive 리스트(`arm_timeout`, `disarm_timeout`, `expired`, `has_timed`)와 가장 이른 기한의 하한을 유지하므로, 대부분의 틱은 리스트를 훑지 않습니다. 태스크가 블록 상태를 벗어나는 길은 두 가지뿐이며, 둘 다 태스크를 리스트에서 제거합니다. + +- `k0_sched::enqueue`(깨우기). 메시지로 깨어난 대기자는 기한을 남기지 않습니다. +- `k0_ipc::teardown`(죽음) + +기한이 지난 대기자는 `k0_ipc::expire_timeouts`가 처리합니다. 대기자를 엔드포인트 큐에서 빼고 `TIMEOUT`으로 깨우거나, 그 응답을 쥔 태스크의 응답 링크를 지우고 `REPLY_TIMEOUT`으로 깨웁니다. 링크가 상태와 맞지 않으면 해체와 마찬가지로 커널은 `k0: FATAL`을 출력하고 정지합니다. 이 함수는 타이머 틱마다 실행됩니다. + +- 태스크가 실행 중이었다면 `k0_preempt`에서 +- 실행 중인 태스크가 없었다면 idle 루프에서 + +순회 비용은 인터럽트를 마스크한 상태에서 O(기한이 있는 대기자 수)이며 틱당 최대 한 번입니다. + +> [!NOTE] +> EL0는 여전히 어떤 하드웨어 카운터나 타이머도 읽을 수 없습니다. 타임아웃은 EL0에 스케줄러 틱만큼 거친 시계와 타이머 인터럽트에 맞춰진 깨어남을 줍니다. 이것이 캐시 또는 투기 실행 공격에 쓸 만한 시간 소스로 증폭될 수 있는지는 분석하지 않았습니다. + ## 블록과 교착 -기다려야 하는 태스크는 블록 상태로 표시되어 엔드포인트 큐에 연결되거나 응답 자격에 붙잡힙니다. 그 뒤 스케줄러가 다음 준비 태스크로 전환합니다([scheduling_KR.md](scheduling_KR.md) 참고). 이 태스크의 반환 레지스터는 나중에 해제하는 태스크가 기록합니다. +기다려야 하는 태스크는 블록 상태로 표시되어 엔드포인트 큐에 연결되거나 응답 자격에 붙잡힙니다. 호출에 타임아웃이 있으면 태스크는 기한 목록에도 들어갑니다. 그 뒤 스케줄러가 다음 준비 태스크로 전환합니다([scheduling_KR.md](scheduling_KR.md) 참고). 이 태스크의 반환 레지스터는 나중에 해제하는 태스크가 기록합니다. + +그 시점에 준비된 태스크가 없어도 커널은 멈추지 않습니다. 커널은 `idle_until_ready`(`kernel/src/syscall.rs`)에서 idle 상태로 기다립니다. 다음 인터럽트까지 기다렸다가 기한이 지난 대기자를 모두 깨우고, 준비된 태스크가 있으면 그 태스크로 전환합니다. 그동안에도 타이머 틱은 계속 세고 처리합니다. idle 루프는 다음 두 줄 가운데 하나를 부팅당 최대 한 번씩 출력합니다. -그 시점에 준비된 태스크가 없다면 모든 태스크가 블록된 것입니다. K0에는 아직 인터럽트용 Notification 오브젝트가 없으므로 어떤 것도 태스크를 깨울 수 없습니다. 커널은 `k0: all tasks blocked`를 출력하고 코어를 파킹합니다. +- `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`로 시작하는 줄을 모두 실패로 처리합니다. > [!WARNING] -> 시스템 전체를 멈추는 것은 fail-secure한 선택이지만, 이것은 [SECURITY_KR.md](../../SECURITY_KR.md)의 어드바이저리 GHSA-q99x-2wrv-358p이기도 합니다. 한 태스크가 마지막으로 블록되어 머신을 멈출 수 있습니다. 엔드포인트 케이퍼빌리티를 가진 격리 태스크도 이렇게 할 수 있으며, 격리는 가용성을 보장하지 않습니다. +> 모든 태스크가 블록되어도 커널은 더 이상 정지하지 않으며, 태스크는 타임아웃으로 자신의 대기에 상한을 걸 수 있습니다. 그래도 가용성은 보호되지 않습니다. 타임아웃 없이 기다리는 태스크는 상대방이 동작하지 않으면 영원히 기다릴 수 있고, 엔드포인트 케이퍼빌리티를 가진 격리 태스크는 여전히 다른 태스크를 기다리게 만들 수 있습니다. 이것이 [SECURITY_KR.md](../../SECURITY_KR.md)의 어드바이저리 GHSA-q99x-2wrv-358p의 주제입니다. 어드바이저리는 릴리즈 시점에 갱신합니다. -태스크 격리로도 이 점은 달라지지 않습니다. +응답을 유지해야 하는 서버나 루트 태스크는 모든 대기에 타임아웃을 지정해야 합니다. 태스크 격리로도 이 점은 달라지지 않습니다. ## 오류 @@ -124,6 +173,9 @@ K0의 IPC는 seL4 방식의 **동기 랑데부**입니다. 메시지는 레지 | `WOULD_BLOCK` | `NONBLOCK`이 지정됐고 상대가 준비되지 않음 | | `NO_REPLY` | `CALL`의 수신자가 응답하지 않고 종료했거나, 폴트를 냈거나, 더 새로운 `CALL`을 받았거나, 파괴됨 | | `REVOKED` | 호출자가 줄 서 있는 동안 엔드포인트의 원본 케이퍼빌리티가 삭제됨 | +| `TIMEOUT` | 상대가 오기 전에 대기가 끝났고, 메시지는 전달되지 않음 | +| `REPLY_TIMEOUT` | `CALL`은 전달됐지만 제때 응답이 오지 않았고, 서버가 동작했는지는 알 수 없음 | +| `BAD_FLAGS` | 플래그 레지스터의 예약 비트(31부터 1)가 설정됨 | ## 테스트 방법 @@ -136,6 +188,17 @@ IPC와 해체는 부팅으로 테스트합니다. 루트 태스크는 서버 태 - 응답 자격을 아직 가진 채 새 `CALL`을 받는 서버, 그래서 첫 번째 호출자가 `NO_REPLY`를 받는 경우 - 호출자가 기다리는 동안 종료되는 서버, 그래서 호출자가 `NO_REPLY`를 받는 경우 +타임아웃 테스트(`userspace/root-task/src/main.rs`의 `test_timeouts`)는 실제 틱을 기다리며 다음을 검사합니다. + +- 예약된 플래그 비트가 거부되는지, `NONBLOCK`이 타임아웃보다 우선하는지 +- 서버가 끝내 응답하지 않는 `CALL`이, 다른 모든 태스크도 블록된 상태에서 `REPLY_TIMEOUT`을 반환하는지 +- `RECV`, `SEND`, `CALL`에서 기다리는 대기자 세 개가 `TIMEOUT`을 반환하는지 +- 서버의 뒤늦은 응답이 버려지고 다음 호출이 자기 응답을 받는지 +- 기한이 있는 대기자를 삭제할 수 있는지 +- 메시지로 깨어난 대기자가 기한을 남기지 않는지 + +타임아웃 테스트는 가장 큰 untyped에서 오브젝트를 가져옵니다. 실제 틱을 기다리므로 부팅 테스트는 약 4초 더 걸립니다. + 케이퍼빌리티 테스트는 배지를 한 번만 붙일 수 있고 두 번째는 거부되는지, 복사본이 배지를 유지하는지, 송신 전용 케이퍼빌리티로는 수신할 수 없고 수신 전용으로는 송신할 수 없는지(`NO_RIGHTS`), 엔드포인트를 회수하면 복사본이 모두 사라지고 원본은 남는지를 검사합니다. 격리 테스트는 송신 전용이고 배지가 붙은 엔드포인트 케이퍼빌리티 하나만 CNode에 든 격리 태스크를 시작합니다. 루트 태스크는 그 태스크가 `x1`로 자신에게 주어진 배지를 받는지, 그리고 루트 태스크의 슬롯 번호가 격리 CNode에서 아무 의미가 없는지(`BAD_SLOT`)를 검사합니다. @@ -151,12 +214,16 @@ IPC와 해체는 부팅으로 테스트합니다. 루트 태스크는 서버 태 부팅 테스트 스크립트는 `k0: task fault` 줄의 개수가 정확히 맞고 `k0: unknown syscall` 줄이 정확히 하나일 것도 요구하므로, 파괴된 뒤에도 계속 실행되는 태스크가 있으면 테스트가 실패합니다. -`tools/qemu-boot-test.sh`는 `root: ipc tests pass`를 요구합니다. +`tools/qemu-boot-test.sh`는 `root: ipc tests pass`, `k0: idle (waiting for a timeout)`, `root: timeout tests pass`를 요구합니다. 시리얼 포트로 판정할 때는 `root: teardown tests pass`와 `root: timeout tests pass` 사이의 타이머 틱 줄도 셉니다. 적어도 4개가 있어야 하며, EL0에는 시계가 없으므로 이것이 타임아웃의 하한을 확인하는 방법입니다. ## 알려진 공백 > [!NOTE] -> IPC를 통한 케이퍼빌리티 전송은 아직 없습니다. 알림과 타임아웃도 아직 없으므로, 블록된 태스크는 상대방이 동작할 때까지 기다립니다. +> IPC를 통한 케이퍼빌리티 전송과 Notification 오브젝트는 아직 없습니다. 타임아웃은 호출마다 선택하는 것이므로, 타임아웃 없이 기다리는 태스크는 여전히 상대방이 동작할 때까지 기다립니다. +- **타임아웃은 태스크가 준비되는 시점이지 실행되는 시점이 아님**: 우선순위도 CPU 예산도 없으며, 스케줄러는 1틱 슬라이스의 라운드 로빈입니다([scheduling_KR.md](scheduling_KR.md) 참고). +- **긴 시스템 콜**: 커널은 선점되지 않으므로, 객체가 많은 untyped에 대한 `CAP_REVOKE` 같은 긴 호출은 다른 모든 태스크와 모든 타임아웃을 지연시킵니다. +- **치명적 정지**: `k0_arch::fatal`이나 커널 패닉은 여전히 머신을 정지시킵니다. +- **EL0의 시간 소스**: 틱에 맞춰 깨어나는 성질을 타이밍 공격에 쓸 수 있는지는 분석하지 않았습니다. - **큐에 있던 송신자**: 회수 뒤에도 메시지를 한 번 전달합니다. 엔드포인트에서 이미 기다리는 송신자는 자신을 큐에 세운 송신의 배지를 유지합니다. 기다리는 동안 그 케이퍼빌리티가 회수되어도 메시지는 다음 수신자에게 한 번 전달됩니다. - **메시지당 워드 네 개**: 더 큰 데이터는 공유 메모리가 필요합니다. 태스크가 서로 다른 주소 공간에서 실행될 수 있으므로, 공유 메모리는 그 태스크의 `AddrSpace` 케이퍼빌리티를 가진 쪽이 해당 주소 공간에 매핑해 주어야 합니다. diff --git a/design/kr/memory_KR.md b/design/kr/memory_KR.md index 9b7b265..0fb18ac 100644 --- a/design/kr/memory_KR.md +++ b/design/kr/memory_KR.md @@ -6,7 +6,7 @@ -이 노트는 커널이 자기 자신을 매핑하는 방법을 설명합니다. 변환 설정, 정적 테이블 풀, 권한 체계, 그리고 부팅 때 결과를 확인하는 검사를 다룹니다. 코드는 `crates/k0-mm/src/paging.rs`에 있습니다. 사용자 주소 공간은 [user-address-space_KR.md](user-address-space_KR.md)에서 다룹니다. +이 노트는 커널이 자기 자신을 매핑하는 방법을 설명합니다. 변환 설정, 정적 테이블 풀과 테이블 예약 구간, 권한 체계, 그리고 부팅 때 결과를 확인하는 검사를 다룹니다. 코드는 `crates/k0-mm/src/paging.rs`에 있습니다. 사용자 주소 공간은 [user-address-space_KR.md](user-address-space_KR.md)에서 다룹니다. ## 두 개의 절반 @@ -35,12 +35,12 @@ higher-half로 점프한 뒤 커널은 이 매핑들만 사용합니다. ## 정적 테이블 풀 -커널에는 heap이 없습니다. 페이지 테이블은 `.bss`에 있는 **40개 테이블 풀**에서 나오며, 증가만 하는 카운터로 하나씩 내줍니다. MMU를 설정할 때 다음 테이블 세 개를 가져갑니다. +커널에는 heap이 없습니다. 부팅 중 페이지 테이블은 `.bss`에 있는 **40개 테이블 풀**에서 나오며, 증가만 하는 카운터로 하나씩 내줍니다. MMU를 설정할 때 다음 테이블 세 개를 가져갑니다. - 두 절반의 루트 테이블 두 개 - 매핑이 하나도 없는 빈 `TTBR0_EL1` 루트(`null_user_root`) -현재 설치된 주소 공간이 파괴되면 커널은 `TTBR0_EL1`을 이 빈 루트로 옮겨, 하드웨어가 이미 사라진 테이블을 워크하는 일이 없게 합니다. 그 밖의 테이블은 매핑이 추가되면서 중간 테이블이 됩니다. 기본 빌드를 QEMU virt에서 돌리면 부트 프레임 윈도우를 매핑한 뒤 출력되는 부팅 로그 줄 `k0: kernel table pool N/40`이 `16/40`을 보여 줍니다. 이후 `RETYPE` 호출로 더 늘어날 수 있습니다. +현재 설치된 주소 공간이 파괴되면 커널은 `TTBR0_EL1`을 이 빈 루트로 옮겨, 하드웨어가 이미 사라진 테이블을 워크하는 일이 없게 합니다. 그 밖의 테이블은 매핑이 추가되면서 중간 테이블이 됩니다. 기본 빌드를 QEMU virt에서 돌리면 부트 프레임 윈도우를 매핑한 뒤 출력되는 부팅 로그 줄 `k0: kernel table pool N/40`이 `16/40`을 보여 줍니다. 이 풀은 부팅 중에만 쓰입니다. 부팅 뒤 `RETYPE`에 드는 테이블은 테이블 예약 구간에서 나옵니다("테이블 예약 구간" 참고). 워크가 기존 테이블 엔트리를 따라갈 때, `index_of`는 그 엔트리에 든 주소를 풀 인덱스로 되돌립니다. 풀 안에서 할당된 테이블에 정확히 맞지 않는 주소는 거부합니다. 따라서 손상되었거나 위조된 테이블 주소는 `BadTable`로 워크를 멈추게 하며, 임의의 메모리로 따라 들어가는 일은 없습니다. @@ -48,11 +48,27 @@ higher-half로 점프한 뒤 커널은 이 매핑들만 사용합니다. `map_page`는 내려가는 길에 만든 모든 링크를 기억합니다. 풀이 바닥나거나 리프 엔트리가 이미 사용 중인 경우 등으로 워크가 실패하면, 그 링크를 지우고 카운터를 되돌립니다. 풀은 호출 전과 정확히 같은 상태로 돌아갑니다. -부팅 이후에 이것이 중요합니다. `RETYPE` 시스템 콜마다 이 풀을 통해 새 오브젝트를 커널 별칭에 매핑합니다. 롤백이 없다면 사용자 태스크가 도중에 실패하는 retype을 반복해서 풀을 테이블 몇 개씩 고갈시킬 수 있고, 결국 커널 자신이 아무것도 매핑하지 못하게 됩니다. 롤백이 있으면 실패한 retype은 비용이 들지 않습니다. 호스트 테스트 두 개가 이를 보여 줍니다. +부팅 이후에 이것이 중요합니다. `RETYPE` 시스템 콜마다 새 오브젝트를 커널 별칭에 매핑하는데, 롤백은 정적 배열의 테이블뿐 아니라 예약 구간에서 가져온 테이블도 되돌립니다. 롤백이 없다면 사용자 태스크가 도중에 실패하는 retype을 반복해서 테이블을 몇 개씩 고갈시킬 수 있고, 결국 커널 자신이 아무것도 매핑하지 못하게 됩니다. 롤백이 있으면 실패한 retype은 비용이 들지 않습니다. 호스트 테스트 두 개가 이를 보여 줍니다. - 하나는 워크를 중간에 실패시키고 풀이 그대로인지 확인합니다. - 다른 하나는 거의 가득 찬 풀에서 천 번 연속으로 실패시킵니다. +## 테이블 예약 구간 + +retype된 오브젝트의 커널 별칭에 드는 테이블은 정적 풀에서 나오지 않습니다. 부팅 때 `Untyped` 케이퍼빌리티가 될 메모리 구간마다, 커널은 그 구간의 모든 그래뉼을 매핑하는 데 들 수 있는 최대 테이블 수를 계산해 그만큼의 그래뉼을 구간 안에 따로 떼어 둡니다. + +- `alias_tables_for`는 구간에 대한 상한을 줍니다. 루트 아래 세 레벨마다 구간이 걸치는 블록의 수를 세므로, 실제로 드는 수가 이 값을 넘는 일은 없습니다. +- 커널은 이 몫을 구간의 맨 위에서 떼어 `reserve_tables`로 등록합니다. 몫 아래의 나머지 구간이 `Untyped`으로 넘어갑니다. 몫에는 주소 공간 등록부 항목도 함께 있습니다([user-address-space_KR.md](user-address-space_KR.md) 참고). +- 예약 구간은 최하위 테이블 하나가 덮는 크기의 조각 단위로 스스로를 매핑하며, 조각이 매핑되는 즉시 등록합니다. 첫 조각만 그 시점에 있는 것(정적 풀 또는 앞서 등록한 예약 구간)에서 치르고, 나머지는 구간이 스스로 댑니다. +- 테이블 번호는 정적 배열에서 이어서 예약 구간들로 계속되며, 예약 구간이 등록된 순서를 따릅니다. `index_of`는 배열이나 예약 구간에서 이미 내준 테이블의 주소만 받아들입니다. +- 예약 구간의 테이블은 부팅 때가 아니라 **내줄 때 소거**합니다. +- 워크가 실패하면 롤백이 두 곳의 테이블을 모두 돌려줍니다. + +부팅 뒤 `alias_object`는 예약 구간에서 테이블을 가져옵니다. 커널이 `Untyped`으로 넘긴 구간 안의 어떤 주소에 대해서도 테이블이 모자라 실패하는 일은 없습니다. 자기 몫을 둘 수 없거나 몫을 매핑할 수 없는 구간은 `Untyped`으로 **넘기지 않습니다**. 커널은 `k0: memory + not handed out ()`를 출력하고 부팅을 계속합니다. 온전한 그래뉼이 하나도 없는 틈은 오브젝트를 만들 수 없으므로 그대로 넘깁니다. + +> [!NOTE] +> 예약 구간의 비용은 4 KiB 그래뉼에서 메모리 2 MiB당 테이블 하나(RAM의 약 0.2 %), 16 KiB 그래뉼에서 32 MiB당 하나(약 0.05 %)입니다. + ## 권한 > [!IMPORTANT] @@ -136,12 +152,13 @@ DTB는 헤더를 검사한 뒤에야 별칭으로 읽기 전용 매핑되고, ## 테스트 방법 - `tools/boot-matrix.sh`는 기본 빌드와 16 KiB 빌드를 여러 QEMU 구성에서 부팅하고, 지원하지 않는 구성이 부팅 로그에 사유를 남기며 거부되는지 확인합니다. -- `crates/k0-mm/src/paging/tests.rs`의 호스트 단위 테스트는 두 그래뉼의 인덱스 산술, 모든 커널 권한의 W^X 속성, 실패한 워크 이후의 롤백, 위조되었거나 블록인 엔트리의 거부, 완전히 같은 리프가 호출자가 요청할 때만 받아들여지는지(`an_identical_leaf_is_accepted_only_when_asked`)를 확인합니다. AArch64 호스트에서 실행됩니다. +- `crates/k0-mm/src/paging/tests.rs`의 호스트 단위 테스트는 두 그래뉼의 인덱스 산술, 모든 커널 권한의 W^X 속성, 실패한 워크 이후의 롤백(예약 구간의 테이블 포함), 위조되었거나 블록인 엔트리의 거부, 예약 구간 테이블을 내줄 때의 소거, 여러 예약 구간에 걸친 번호 매김, 첫 조각을 매핑하지 못하는 예약 구간(등록되지 않음), 완전히 같은 리프가 호출자가 요청할 때만 받아들여지는지(`an_identical_leaf_is_accepted_only_when_asked`)를 확인합니다. AArch64 호스트에서 실행됩니다. +- 호스트 속성 테스트(`aliasing_every_granule_of_any_ranges_stays_within_the_bound`)는 블록 경계 근처의 무작위 구간을 뽑아 정적 배열을 닫고, 모든 구간의 모든 그래뉼을 매핑한 뒤 `alias_tables_for`가 준 수보다 많은 테이블이 쓰이지 않았는지 확인합니다. +- 루트 태스크 자체 테스트 `test_reserve`는 최대 40개 테이블 블록에 걸쳐 프레임을 retype하고 어떤 `RETYPE`도 `KERNEL_RESOURCE`로 실패하지 않을 것을 요구합니다. 마커 `root: kernel reserve tests pass`와 부팅 줄 `k0: kernel reserve `가 필요합니다. - `tools/qemu-boot-test.sh`는 `k0: w^x checks pass` 줄을 요구합니다. ## 알려진 공백 -- **풀 고갈**: 풀 크기는 40개 테이블로 고정입니다. retype이 충분히 많은 서로 다른 주소 범위에 흩어지면 풀이 바닥나고 `RETYPE`은 `KERNEL_RESOURCE`를 반환합니다. 누수는 없지만 풀은 회수되지 않습니다. -- **별칭 잔존**: 커널 별칭 매핑은 제거되지 않습니다. retype된 오브젝트는 케이퍼빌리티가 revoke되고 그 메모리가 다시 retype된 뒤에도 커널 별칭에 매핑된 채 남습니다. 완전히 같은 별칭은 받아 주므로 재사용은 더 이상 실패하지 않지만, 별칭과 그것을 담은 테이블은 그대로 남습니다. -- **가용성 한계**: 위 두 가지 때문에, untyped 메모리를 많이 가진 태스크는 충분히 많은 서로 다른 주소 범위에 retype하여 풀을 소진시킬 수 있습니다. 그러면 `RETYPE`은 원인 태스크뿐 아니라 모든 태스크에 `KERNEL_RESOURCE`를 반환합니다. 태스크 간 격리는 이 가용성 한계를 다루지 않습니다. +- **별칭 잔존**: 커널 별칭 매핑은 제거되지 않습니다. retype된 오브젝트는 케이퍼빌리티가 revoke되고 그 메모리가 다시 retype된 뒤에도 커널 별칭에 매핑된 채 남습니다. 완전히 같은 별칭은 받아 주므로 재사용은 실패하지 않지만, 별칭과 그것을 담은 테이블은 그대로 남습니다. 예약 구간은 이를 감안해 넘겨진 모든 구간의 모든 그래뉼을 한 번씩 덮도록 잡습니다. +- **가용성**: retype으로 커널 테이블을 소진시킬 수는 없게 되었지만, 가용성 전반은 여전히 보호되지 않습니다. 스케줄러에는 우선순위와 CPU 예산이 없고, 긴 시스템 콜은 다른 모든 태스크를 지연시킵니다. 태스크 간 격리는 가용성을 다루지 않습니다. - **ASID 없음**: 주소 공간 식별자(ASID)는 사용하지 않습니다. 다른 사용자 주소 공간으로 전환할 때마다 TLB 전체를 무효화합니다. diff --git a/design/kr/scheduling_KR.md b/design/kr/scheduling_KR.md index 53b29d2..7fbae2b 100644 --- a/design/kr/scheduling_KR.md +++ b/design/kr/scheduling_KR.md @@ -31,6 +31,7 @@ - **큐 링크**: 태스크가 속한 큐에서 이웃 TCB로 가는 `next`와 `prev`입니다. - **응답 자격**: 1회성 응답 자격(`reply_to`)과 그 역방향 링크(`reply_from`)입니다. [ipc_KR.md](ipc_KR.md)에서 설명합니다. - **IPC 대기 정보**: 태스크가 줄 서 있는 엔드포인트 `blocked_on`, 그리고 보내려는 메시지에 붙을 배지 `ipc_badge`입니다. +- **타임아웃 필드**: 태스크의 IPC 대기가 끝나는 틱 `deadline`, 그리고 기한 목록의 링크 `tnext`와 `tprev`입니다([타임아웃](#타임아웃) 참고). - **내장 케이퍼빌리티 슬롯 3개**: 1번 슬롯은 태스크의 `CNode` 케이퍼빌리티, 2번 슬롯은 `AddrSpace` 케이퍼빌리티를 담습니다. 0번 슬롯은 사용하지 않습니다. **내장 슬롯**이 태스크를 케이퍼빌리티 공간과 주소 공간에 묶습니다. 시스템 콜은 슬롯 번호를 1번 슬롯의 CNode 안에서만 해석하고([capabilities_KR.md](capabilities_KR.md) 참고), 태스크는 2번 슬롯이 가리키는 주소 공간에서 실행됩니다. 둘 다 `TCB_CONFIGURE`에 넘긴 케이퍼빌리티의 복사본, 즉 파생 리스트에서 그 자식이며, 태스크에 묶인 것으로 표시됩니다. 둘 중 하나라도 제거되면 태스크는 정리됩니다([정리](#정리) 참고). @@ -44,7 +45,7 @@ 다음 그림은 태스크 상태와 전환을 보여 줍니다. 각 상태의 의미는 그다음 표에 있습니다.

- Inactive에서 TCB_CONFIGURE로 Stopped, TCB_RESUME으로 Ready가 되고, 라운드 로빈으로 Running과 Ready를 오가며, IPC에서 블록되었다가 해제되면 Ready가 되고, 어느 상태에서든 정리되면 Dead가 되는 모습 + Inactive에서 TCB_CONFIGURE로 Stopped, TCB_RESUME으로 Ready가 되고, 라운드 로빈으로 Running과 Ready를 오가며, IPC에서 블록되었다가 상대가 해제하거나 기한이 지나면 Ready가 되고, 어느 상태에서든 정리되면 Dead가 되는 모습

| 상태 | 의미 | @@ -57,6 +58,8 @@ | `BlockedReply` | `CALL`의 응답을 기다리는 중 | | `Dead` | 종료, 강제 종료, 또는 정리됨 | +블록 상태의 태스크는 기한이 지나도 `Ready`가 될 수 있습니다([타임아웃](#타임아웃) 참고). + `Inactive`의 값은 0입니다. 방금 retype한 프레임은 전부 0이므로, 큐 링크가 비어 있고 내장 슬롯이 비어 있으며 응답 자격이 없는 유효한 `Inactive` TCB입니다. retype에 생성자가 필요 없습니다. ## 태스크 생성 @@ -99,7 +102,7 @@ | 동작 | 사용처 | 현재 태스크에 일어나는 일 | | --- | --- | --- | | `rotate` | `YIELD`, 타이머 선점 | 준비 큐의 꼬리로 가고, 준비된 다른 태스크가 없으면 그대로 계속 실행 | -| `block_and_switch` | IPC, 그리고 현재 태스크가 죽었을 때의 시스템 콜 종료 경로 | 준비 큐 밖에 머뭅니다. 호출자가 이미 엔드포인트 큐나 응답 자격 뒤에 걸어 두었거나, 태스크가 `Dead`입니다. | +| `block_and_switch` | IPC, idle 루프, 그리고 현재 태스크가 죽었을 때의 시스템 콜 종료 경로 | 준비 큐 밖에 머뭅니다. 호출자가 이미 엔드포인트 큐나 응답 자격 뒤에 걸어 두었거나, 태스크가 `Dead`입니다. | | `handoff` | 부트, 한 번 | 루트 태스크가 첫 `Running` 태스크가 됨 | ## 선점 @@ -111,6 +114,15 @@ EL1에서 타이머 인터럽트가 도착하는 것은 이양 전 부트 중에만 가능하며, 그때는 틱을 세기만 합니다. +## 타임아웃 + +틱은 [ipc_KR.md](ipc_KR.md)에서 설명하는 모든 IPC 타임아웃의 단위입니다. 스케줄러는 기한이 있는 대기자를 기한 목록(`k0-sched`의 `arm_timeout`, `disarm_timeout`, `expired`, `has_timed`)에 유지합니다. 이 리스트는 정렬되어 있지 않고, 가장 이른 기한의 하한 덕분에 대부분의 틱은 리스트를 건너뜁니다. + +태스크가 블록 상태를 벗어나는 길은 `k0_sched::enqueue`(깨우기)와 `k0_ipc::teardown`(죽음)뿐이며, 둘 다 태스크를 기한 목록에서 제거합니다. 타이머 틱마다 `k0_ipc::expire_timeouts`가 기한이 지난 대기자를 깨웁니다. 태스크가 실행 중이었다면 `k0_preempt`에서, 없었다면 idle 루프에서 실행됩니다. n 틱의 타임아웃은 호출 뒤 (n+1)번째 틱에서 끝납니다. + +> [!NOTE] +> 타임아웃은 태스크가 준비되는 시점이지 실행되는 시점이 아닙니다. 깨어난 태스크는 다른 태스크와 마찬가지로 준비 큐의 꼬리에 들어갑니다. + ## 정리 정리(teardown)는 태스크를 `Dead`로 만들고 그 태스크를 가리키는 모든 커널 포인터를 제거합니다. 다음 경우에 실행됩니다. @@ -131,8 +143,8 @@ EL1에서 타이머 인터럽트가 도착하는 것은 이양 전 부트 중에 | `Dead` | 아무것도 안 함. 두 번 불러도 안전 | | `Inactive`, `Stopped` | 뺄 링크 없음 | | `Ready` | 준비 큐에서 태스크를 뺌 | -| `BlockedSend`, `BlockedRecv`, `BlockedCall` | `blocked_on`이 가리키는 엔드포인트 큐에서 태스크를 뺌 | -| `BlockedReply` | 응답 자격을 쥔 태스크(`reply_from`)에서 그 자격을 지움 | +| `BlockedSend`, `BlockedRecv`, `BlockedCall` | `blocked_on`이 가리키는 엔드포인트 큐에서 태스크를 빼고, 기한이 있으면 기한 목록에서도 뺌 | +| `BlockedReply` | 응답 자격을 쥔 태스크(`reply_from`)에서 그 자격을 지우고, 기한이 있으면 기한 목록에서도 뺌 | | `Running` | 뺄 링크 없음. 뒤의 설명 참고 | 모든 상태에서 이어서 태스크 자신이 쥔 응답 자격을 철회하므로, 그 응답을 기다리던 호출자는 `NO_REPLY`로 깨어나 영원히 블록되지 않습니다. 마지막으로 상태를 `Dead`로 바꾸고, 큐 링크, `blocked_on`, `reply_from`, `ipc_badge`, `ttbr0_pa`를 지우며, `Running`이 아니면 저장된 레지스터를 0으로 지웁니다. 상태가 약속하는 것과 큐나 응답 링크가 맞지 않으면 커널 불변식 위반이므로 커널은 `k0: FATAL ...`을 출력하고 정지합니다([exceptions_KR.md](exceptions_KR.md) 참고). @@ -143,13 +155,21 @@ EL1에서 타이머 인터럽트가 도착하는 것은 이양 전 부트 중에 ## 실행할 태스크가 없을 때 -- **현재 태스크가 죽은 경우**: 커널 진입 중에 현재 태스크가 죽었는데 준비된 태스크가 없으면 `finish`가 `k0: all tasks exited`를 출력하고 코어를 파킹합니다. -- **현재 태스크가 블록된 경우**: 현재 태스크가 IPC에서 블록됐는데 준비된 태스크가 없으면 `block_and_switch`가 이를 보고하고, 커널은 `k0: all tasks blocked`를 출력한 뒤 파킹합니다. 알림 오브젝트가 아직 없으므로 지금은 다른 어떤 이벤트도 태스크를 깨울 수 없습니다. +실행할 태스크가 없어도 커널은 더 이상 코어를 파킹하지 않습니다. 현재 태스크가 블록됐거나 죽었는데 준비된 태스크가 없으면 `kernel/src/syscall.rs`의 `idle_until_ready`가 다음 순서로 처리합니다. + +1. 다음 인터럽트를 기다립니다(`k0_arch::irq::wait_for_interrupt`: IRQ를 마스크한 `wfi`, 그다음 EL1 벡터가 인터럽트를 받도록 잠깐 마스크 해제). +2. 기한이 지난 IPC 대기자를 모두 깨웁니다. +3. 준비된 태스크가 있으면 그 태스크로 전환하고, 없으면 다시 기다립니다. + +커널이 idle 상태인 동안에도 타이머 틱은 계속 세고 처리합니다. idle 루프는 다음 두 줄 가운데 하나를 부팅당 최대 한 번씩 출력합니다. + +- `k0: idle (waiting for a timeout)`: 기한이 있는 대기자가 하나 이상 있습니다. +- `k0: all tasks stopped (none ready, no timeout pending)`: 기한이 있는 대기자가 없습니다. 지금은 Notification 오브젝트도 태스크용 장치 인터럽트도 없으므로 이 상태에서는 어떤 것도 태스크를 깨울 수 없고, 머신은 idle 상태로 남습니다. > [!WARNING] -> 모든 태스크가 블록되는 경우는 [SECURITY_KR.md](../../SECURITY_KR.md)의 어드바이저리 GHSA-q99x-2wrv-358p입니다. 태스크 격리는 이를 바꾸지 않으며, 마지막으로 블록하는 격리된 태스크가 시스템 전체를 파킹시킬 수 있습니다. 격리는 태스크 사이의 기밀성과 무결성을 지키는 것이지 가용성을 지키지 않습니다. +> 가용성은 여전히 보호되지 않습니다. 타임아웃 없이 기다리는 태스크는 상대방이 동작하지 않으면 영원히 기다릴 수 있고, 마지막으로 블록하는 격리 태스크는 여전히 시스템에 실행할 태스크가 없게 만들 수 있습니다([SECURITY_KR.md](../../SECURITY_KR.md)의 어드바이저리 GHSA-q99x-2wrv-358p, 릴리즈 시점에 갱신). 격리는 태스크 사이의 기밀성과 무결성을 지키는 것이지 가용성을 지키지 않습니다. -파킹은 커널 안의 `wfe` 루프이며, 커널은 인터럽트를 마스크한 채 실행됩니다. +EL0에서 받은 SError는 여전히 머신 전체를 정지시키며, `k0_arch::fatal`이나 커널 패닉도 마찬가지입니다. ## 테스트 방법 @@ -162,17 +182,18 @@ EL1에서 타이머 인터럽트가 도착하는 것은 이양 전 부트 중에 - 자기 CNode와 자기 주소 공간을 가진 격리 태스크를 만들고, 루트 태스크의 슬롯 번호가 거기서 아무 의미가 없는지 확인 - 모든 상태(inactive, stopped, ready, send·receive·call에서 블록, 응답 대기, 응답 자격 보유, 엔드포인트 큐의 머리·중간·꼬리)의 태스크 삭제, 태스크가 줄 서 있는 엔드포인트 삭제, CNode 회수 또는 주소 공간 삭제로 태스크 종료, 태스크가 자기 TCB를 삭제하고 자신이 잘려 나온 untyped를 회수하는 경우 -`tools/qemu-boot-test.sh`는 마커 `root: child exit test pass`, `root: preempt test pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: revocation tests pass`, `root: sched tests pass`를 요구하고, 그 뒤에 타이머 틱이 적어도 하나 더 나와야 합니다. 로그에 `k0: all tasks`, `k0: FATAL`, `k0: PANIC`이 있으면 실패하므로 너무 일찍 나온 "all tasks exited"는 실패로 처리됩니다. 태스크 폴트 줄도 정확한 개수로 세므로([exceptions_KR.md](exceptions_KR.md) 참고), 정리된 뒤에도 계속 실행되는 태스크를 잡아냅니다. +`tools/qemu-boot-test.sh`는 마커 `root: child exit test pass`, `root: preempt test pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: revocation tests pass`, `root: sched tests pass`를 요구하고, 그 뒤에 타이머 틱이 적어도 하나 더 나와야 합니다. 마커에는 타임아웃 테스트가 출력하는 `k0: idle (waiting for a timeout)`와 `root: timeout tests pass`도 포함됩니다([ipc_KR.md](ipc_KR.md) 참고). 로그에 `k0: all tasks`로 시작하는 줄, `k0: FATAL`, `k0: PANIC`이 있으면 실패하므로 실행할 태스크도 대기 중인 타임아웃도 없는 상태에 이른 실행은 실패로 처리됩니다. 태스크 폴트 줄도 정확한 개수로 세므로([exceptions_KR.md](exceptions_KR.md) 참고), 정리된 뒤에도 계속 실행되는 태스크를 잡아냅니다. ## 알려진 공백 > [!NOTE] -> 우선순위, 예산, 타임아웃, idle 상태는 아직 없습니다. 코어는 하나뿐입니다. +> 우선순위와 CPU 예산은 아직 없습니다. 코어는 하나뿐입니다. -- **스케줄링**: 1초 고정 슬라이스의 단순 라운드 로빈입니다. -- **idle 상태가 없을 때의 동작**: 루트 태스크는 자가 테스트를 마치면 `YIELD`를 계속 호출하므로 CPU가 잠들지 않습니다. 실행할 태스크가 없을 때 커널은 이벤트를 기다리지 않고 파킹합니다. -- **가용성**: 모든 태스크가 블록되면 커널은 코어를 파킹하며, 격리된 태스크가 마지막으로 블록해서 이를 일으킬 수 있습니다(GHSA-q99x-2wrv-358p). 태스크 격리는 가용성을 다루지 않습니다. -- **블록된 태스크**: IPC 상대가 동작하거나 엔드포인트가 삭제될 때만 깨어납니다. +- **스케줄링**: 1초 고정 슬라이스의 단순 라운드 로빈입니다. untyped 메모리를 가진 태스크는 태스크를 많이 만들어 모두의 몫을 희석시킬 수 있습니다. +- **타임아웃**: 태스크가 준비되는 시점을 정할 뿐 실행되는 시점을 정하지 않습니다. 호출마다 선택하는 것이므로 타임아웃 없이 기다리는 태스크는 영원히 기다릴 수 있습니다. +- **idle 상태**: 있지만, 루트 태스크가 자가 테스트 뒤에 `YIELD`를 계속 호출하는 동안에는 CPU가 잠들지 않습니다. 준비된 태스크도 기한이 있는 대기자도 없으면 머신은 idle 상태로 남고 어떤 것도 태스크를 깨울 수 없습니다. +- **가용성**: 타임아웃 없이 블록하는 태스크는 격리 태스크를 포함해 상대방이 동작하지 않으면 계속 블록된 채로 남을 수 있습니다(GHSA-q99x-2wrv-358p). 커널은 선점되지 않으므로 객체가 많은 untyped에 대한 `CAP_REVOKE` 같은 긴 시스템 콜은 다른 모든 태스크와 모든 타임아웃을 지연시킵니다. 태스크 격리는 가용성을 다루지 않습니다. +- **블록된 태스크**: IPC 상대가 동작하거나, 기한이 지나거나, 엔드포인트가 삭제되면 깨어납니다. - **죽은 TCB**: 정리가 회수하지 않습니다. 프레임은 케이퍼빌리티를 삭제하거나 untyped를 회수한 뒤 다시 retype할 때만 재사용됩니다. - **주소 공간 식별자**: 하드웨어 주소 공간 식별자를 사용하지 않으므로 주소 공간 사이의 전환마다 TLB 전체를 비웁니다. - **죽은 태스크**: 다시 시작할 수 없습니다. 새 태스크에는 새 TCB가 필요합니다. diff --git a/design/kr/uefi_KR.md b/design/kr/uefi_KR.md index 07ac33d..badde47 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 호스트에서 221개(`k0-abi` 12, `k0-cap` 41, `k0-boot` 76, `k0-efi` 32, 두 그래뉼 각각에 `k0-mm` 30)를, `k0-mm` 테스트를 건너뛰는 x86-64 호스트에서 161개를 실행합니다. +- **호스트 테스트 스크립트**: `tools/host-test.sh`는 이제 ARM 호스트에서 250개(`k0-abi` 14, `k0-cap` 42, `k0-boot` 76, `k0-efi` 32, 두 그래뉼 각각에 `k0-mm` 43)를, `k0-mm` 테스트를 건너뛰는 x86-64 호스트에서 164개를 실행합니다. - **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/user-address-space_KR.md b/design/kr/user-address-space_KR.md index 3af5810..d36946f 100644 --- a/design/kr/user-address-space_KR.md +++ b/design/kr/user-address-space_KR.md @@ -84,7 +84,16 @@ ### 등록부 -`k0-mm`의 정적 등록부(`AddrSpaces`, `MAX_ADDR_SPACES`개 항목, 0번은 쓰지 않음)가 살아 있는 모든 주소 공간에 번호(`asid`)와 세대를 줍니다. 루트 태스크의 주소 공간은 `kernel_main`에서, 나머지는 `sys_retype`에서 등록합니다. 빈 항목은 배열 안의 단일 연결 목록으로 엮여 있어 등록과 해제에 탐색이 없습니다. 해제하면 세대가 올라갑니다. 세대를 더 올릴 수 없게 된 항목은 퇴역시켜 다시는 내주지 않습니다. 등록부가 가득 차면 `AddrSpace`의 `RETYPE`이 실패합니다. +`k0-mm`의 등록부(`AddrSpaces`)는 부팅 때 크기가 정해집니다. untyped 메모리로 넘기는 **모든 구간의 그래뉼마다 8바이트 항목이 하나씩** 있습니다. 항목은 세대 카운터와 "살아 있음" 비트입니다. 항목은 커널 페이지 테이블과 같은 구간 맨 위 예약 영역에 있고([memory_KR.md](memory_KR.md) 참고) 부팅 때 소거합니다. + +- 주소 공간의 번호(`asid`)는 그 루트 테이블이 놓인 그래뉼의 번호(`root_pa / GRANULE`)이고 `u64`입니다. `Cap::AddrSpace`와 매핑 기록에서 같은 번호를 씁니다. +- 주소 공간을 해제하면 세대가 올라갑니다. 따라서 옛 `(asid, generation)` 쌍은 같은 그래뉼에 새 주소 공간이 생겨도 다시는 일치하지 않습니다. +- 루트 태스크의 주소 공간은 루트 테이블이 untyped 메모리가 아니라 부트 윈도우에 있습니다. 전용 항목 하나(`register_boot`)를 쓰며 `kernel_main`에서 등록합니다. 나머지는 `sys_retype`에서 등록합니다. +- 주소 공간 하나는 루트로 그래뉼 하나가 필요하므로, 메모리가 허락하는 모든 주소 공간에는 항목이 있습니다. **주소 공간의 수에는 메모리 말고 다른 한도가 없고**, `AddrSpace`의 `RETYPE`이 빈 항목이 모자라 실패하는 일은 없습니다. +- 더 올릴 수 없게 된 세대는 포화합니다. 그 그래뉼은 퇴역해 다시는 주소 공간의 루트가 되지 않습니다. 다른 그래뉼에는 영향이 없습니다. + +> [!NOTE] +> 항목의 비용은 그래뉼마다 8바이트로, 4 KiB 그래뉼에서 RAM의 약 0.2 %, 16 KiB 그래뉼에서 약 0.05 %입니다. 부팅 로그 줄 `k0: kernel reserve tables + address space entries = bytes in ranges`가 합계를 보여 줍니다. `Frame`이나 `PageTable` 케이퍼빌리티는 자신이 매핑된 위치를 `(asid, 세대, va, 레벨)` 기록으로 기억하며, 포인터는 절대 저장하지 않습니다. 주소 공간이 먼저 파괴되면 이 기록은 더 이상 해석되지 않으므로, 커널은 메모리가 이미 다른 용도로 바뀌었을 수 있는 루트 테이블을 걷지 않습니다. @@ -98,7 +107,7 @@ - `user_map_frame`으로 `Frame` 케이퍼빌리티를 **매핑**하면 리프 엔트리 하나를 만듭니다. 도중에 중간 테이블이 없으면 호출은 `MISSING_TABLE`로 실패합니다. 리프는 비어 있어야 하며, 그렇지 않으면 호출은 `OVERLAP`으로 실패합니다. - `user_install_table`로 `PageTable` 케이퍼빌리티를 **매핑**하면 주어진 주소의 경로를 따라 내려가며 처음 만나는 빈 레벨에 테이블을 연결합니다. 경로가 리프 레벨까지 이미 완성되어 있으면 호출은 `OVERLAP`으로 실패합니다. -따라서 사용자 공간은 `PageTable` 오브젝트를 retype하는 방식으로, 자신의 untyped 메모리를 들여 자기 페이지 테이블 비용을 직접 부담합니다. 커널의 정적 테이블 풀은 사용자 매핑에 대해 소모되지 않습니다. +따라서 사용자 공간은 `PageTable` 오브젝트를 retype하는 방식으로, 자신의 untyped 메모리를 들여 자기 페이지 테이블 비용을 직접 부담합니다. 커널 자신의 테이블은 사용자 매핑에 대해 소모되지 않습니다. `sys_map`의 추가 규칙은 다음과 같습니다. @@ -151,7 +160,7 @@ CPU에 FEAT_PAN이 있으면 커널은 PAN을 설정한 채 실행되므로, 사 - 모든 사용자 권한의 W^X 속성 - 어떤 테이블도 건드리기 전에 잘못된 입력을 거부해야 하는 검증 경로 - 호스트 메모리 위에서 도는 실제 워커: 테이블의 위에서 아래 순서 설치(`tables_install_top_down_and_frames_need_the_full_path`), 바로 그 프레임의 리프만 지우는 unmap(`unmap_clears_only_the_leaf_that_maps_this_very_frame`), 링크 하나만 끊는 uninstall(`uninstall_cuts_exactly_one_link_and_a_zeroed_table_carries_nothing`), 무작위 map·unmap 순서에 대한 모델 테스트(`random_map_and_unmap_agree_with_a_model`), 48비트 범위 전체 커버리지입니다. - - 등록부: 서로 다른 0이 아닌 번호, 거부되는 잘못된 번호, 낡은 세대(`a_stale_generation_never_resolves_again`), 무작위 등록·해제 순서, 소진된 세대의 퇴역 + - 등록부: 구간의 모든 그래뉼이 동시에 주소 공간을 가질 수 있음(`every_granule_of_a_range_can_hold_an_address_space_at_once`), 등록부가 다루지 않는 번호의 거부(`registry_rejects_what_it_does_not_cover`), 낡은 세대(`a_stale_generation_never_resolves_again`), 무작위 등록·해제 순서(`registry_survives_random_register_release_sequences`), 소진된 세대의 퇴역(`a_granule_whose_generation_is_exhausted_is_retired`), 루트 태스크의 전용 항목(`the_root_task_address_space_has_its_own_entry`), 서로 독립인 구간과 한도가 있는 구간 표(`ranges_are_independent_and_the_table_of_ranges_is_bounded`) - `tools/host-test.sh`는 `k0-mm`을 AArch64 호스트에서만 두 그래뉼 모두로 실행합니다. - 루트 태스크 자가 테스트는 실행 중 경로를 점검합니다. 점검 항목은 다음과 같습니다. - 페이지 테이블이 생기기 전의 매핑 @@ -167,13 +176,13 @@ CPU에 FEAT_PAN이 있으면 커널은 PAN을 설정한 채 실행되므로, 사 - 떼어 낸 테이블이 옛 리프를 새 자리로 가져가지 않는 것 - 테이블이 분리된 뒤의 낡은 프레임 기록 - 새 매핑을 통한 읽기와 쓰기 + - 주소 공간 300개가 동시에 살아 있는 경우로, 예전 등록부가 담던 수보다 많음(`test_reserve`) - 격리 자가 테스트는 자기 CNode와 자기 주소 공간(이미지 text와 읽기 전용 데이터만 매핑)을 가진 격리 태스크를 만들어, 루트 전용 주소를 읽으면 정확히 그 주소에서 폴트가 나는지, 읽기 전용 페이지 쓰기·스택 페이지 실행·커널 주소 읽기가 폴트를 내는지, 주소 공간이 삭제되면 태스크가 죽는지를 확인합니다. - `tools/qemu-boot-test.sh`는 `k0: user w^x checks pass`, `root: retype/map tests pass`, `root: isolation tests pass`, `root: teardown tests pass`, `root: revocation tests pass` 등을 요구하고, `k0: task fault` 줄의 정확한 개수도 요구합니다. ## 알려진 공백 -- **가용성**: 격리는 가용성을 포함하지 않습니다. 모든 태스크가 막히면 커널은 코어를 파킹하며([SECURITY_KR.md](../../SECURITY_KR.md) 참고), 격리된 태스크가 마지막으로 막힘으로써 이를 일으킬 수 있습니다. -- **등록부와 풀 한도**: 등록부는 최대 `MAX_ADDR_SPACES`개의 주소 공간을 담습니다. retype된 모든 오브젝트의 커널 별칭은 정적 커널 페이지 테이블 풀을 사용합니다. untyped 메모리를 많이 가진 태스크가 이 풀을 고갈시키면 모두에게 `RETYPE`이 `KERNEL_RESOURCE`로 실패합니다. +- **가용성**: 격리는 가용성을 포함하지 않습니다. 모든 태스크가 막혀도 커널은 더 이상 멈추지 않으며, 등록부와 커널 페이지 테이블은 태스크가 소진시킬 수 없게 되었습니다([memory_KR.md](memory_KR.md)와 [SECURITY_KR.md](../../SECURITY_KR.md) 참고). 타임아웃 없이 기다리는 태스크는 여전히 영원히 기다릴 수 있고, 우선순위와 CPU 예산은 없습니다. untyped 메모리를 가진 태스크는 주소 공간과 태스크를 많이 만들어 다른 태스크의 몫을 희석시킬 수 있습니다. - **새 실행 코드**: 설계상(프레임 단위 W^X) 부팅 이후에는 새 실행 코드를 적재할 수 없습니다. 격리된 태스크는 루트 태스크 이미지의 코드만 실행할 수 있습니다. - **하드웨어 ASID**: 하드웨어 ASID가 없으므로 `TTBR0` 전환과 모든 매핑 해제마다 TLB 전체를 비웁니다. 안전이 아니라 성능의 비용입니다. - **커널 별칭**: 사용자 공간에 매핑된 모든 프레임은 커널 별칭에도 읽기·쓰기로 매핑되어 있습니다. retype 중에 커널이 그곳에서 프레임을 0으로 채웠기 때문입니다. diff --git a/kernel/src/main.rs b/kernel/src/main.rs index 684016b..f9dc0f0 100644 --- a/kernel/src/main.rs +++ b/kernel/src/main.rs @@ -290,14 +290,16 @@ extern "C" fn kernel_main(dtb_phys: usize) -> ! { let _ = writeln!(con, "k0: root task loaded (entry {:#x})", root_task.entry); // 루트 주소 공간을 등록부에 올림. 이후 매핑 기록은 (asid, 세대)로 이 - // 주소 공간을 가리킴 + // 주소 공간을 가리킴. 루트 테이블이 untyped 밖(부트 윈도우)에 있어서 + // 등록부의 전용 항목을 씀 // SAFETY: 단일 부트 코어의 초기화 시퀀스라 등록부 접근이 배타적임 - let Some(root_asid) = (unsafe { k0_mm::addr_spaces() }).register(user_root) else { + let Some(root_asid) = (unsafe { k0_mm::addr_spaces() }).register_boot(user_root) else { let _ = writeln!(con, "k0: address space registry failed"); park() }; - // 케이퍼빌리티 부트스트랩: 커널/DTB/윈도우를 뺀 물리 메모리 전부가 untyped + // 케이퍼빌리티 부트스트랩: 커널/DTB/윈도우를 뺀 물리 메모리가 untyped가 됨. + // 다만 구간마다 꼬리에서 커널 몫을 먼저 떼어 둠(reserve_kernel_share) let mut mem_buf = [k0_cap::PhysRegion { base: 0, size: 0 }; k0_boot::MAX_MEM_REGIONS]; for (dst, r) in mem_buf.iter_mut().zip(bootinfo.memory()) { dst.base = r.base; @@ -331,6 +333,14 @@ extern "C" fn kernel_main(dtb_phys: usize) -> ! { dst.size = r.size; } let reserved = &rsv_buf[..FIXED_RSV + bootinfo.reserved().len()]; + let mut ut_buf = [k0_cap::PhysRegion { base: 0, size: 0 }; k0_mm::MAX_TABLE_RESERVES]; + let untyped = match reserve_kernel_share(&mut con, memory, reserved, &mut ut_buf) { + Ok(n) => &ut_buf[..n], + Err(e) => { + let _ = writeln!(con, "k0: cap bootstrap failed: {e:?}"); + park() + } + }; // SAFETY: cnode_frame은 방금 부트 윈도우에서 할당한 소거된 연속 프레임으로 // ROOT_CNODE_SLOTS개의 슬롯을 담고, 단일 부트 코어라 접근이 배타적임 @@ -346,8 +356,9 @@ extern "C" fn kernel_main(dtb_phys: usize) -> ! { addr_space_asid: root_asid, cnode: cnode_frame, }; + // 예약 구간은 위에서 이미 뺐으므로 남은 구간이 그대로 untyped가 됨 // SAFETY: cnode의 슬롯은 전부 비어 있고 접근이 배타적임 - let mut next = match unsafe { k0_cap::bootstrap(&cnode, &objs, memory, reserved) } { + let mut next = match unsafe { k0_cap::bootstrap(&cnode, &objs, untyped, &[]) } { Ok(n) => n, Err(e) => { let _ = writeln!(con, "k0: cap bootstrap failed: {e:?}"); @@ -458,6 +469,141 @@ struct ImageMap { len: u64, } +/// untyped로 넘길 구간을 구하고, 구간마다 꼬리에서 커널 몫을 떼어 두는 +/// 함수입니다. +/// +/// 커널 몫은 두 가지입니다. 하나는 그 구간의 모든 그래뉼을 커널 별칭으로 +/// 매핑하는 데 들 수 있는 페이지 테이블 전부이고, 다른 하나는 그 구간의 +/// 그래뉼마다 하나씩인 주소 공간 등록부 항목입니다. 둘을 부팅 때 구간 크기에 +/// 맞춰 잡아 두므로, 부팅 뒤에는 어떤 태스크도 untyped 메모리를 쥐는 것만으로 +/// 별칭 테이블이나 등록부를 바닥낼 수 없습니다. +/// +/// 구간은 큰 것부터 처리합니다. 꼬리를 매핑하는 데 드는 테이블은 첫 구간만 +/// 정적 풀에서 치르고 그 뒤로는 앞서 등록한 예약에서 나옵니다. 자기 몫을 댈 +/// 수 없는 구간(너무 작거나 매핑에 실패한 구간)은 untyped로 넘기지 않고 한 +/// 줄을 남깁니다. 부팅을 거부하지는 않습니다(UEFI 로더의 사전 검사가 이 +/// 단계를 알지 못하므로 로더가 예측할 수 없는 거부를 만들지 않음). 온전한 +/// 그래뉼이 하나도 없는 틈은 오브젝트를 만들 수 없어 커널 몫도 필요 없으므로 +/// 그대로 넘깁니다. +/// +/// # Arguments +/// `memory` - DTB가 보고한 물리 메모리 구간들 +/// `reserved` - untyped에서 제외할 구간들 +/// `out` - untyped로 넘길 구간을 받을 버퍼 +/// +/// # Errors +/// 구간 산술 위반과 메모리 구간 간 겹침은 `BadRegion`. 성공하면 `out`에 채운 +/// 구간 수를 반환합니다 +fn reserve_kernel_share( + con: &mut EarlyCon, + memory: &[k0_cap::PhysRegion], + reserved: &[k0_cap::PhysRegion], + out: &mut [k0_cap::PhysRegion], +) -> Result { + let g = k0_mm::GRANULE as u64; + k0_cap::check_regions(memory, reserved)?; + + // 버퍼에 다 담지 못한 틈은 넘기지 않음. 커널 몫을 잡지 못한 메모리를 + // untyped로 내주는 것보다 쓰지 않는 쪽이 안전함 + let mut count = 0; + for m in memory { + let _ = k0_cap::for_each_gap(*m, reserved, |gap| -> Result<(), ()> { + if count < out.len() { + out[count] = gap; + count += 1; + } else { + let _ = writeln!( + con, + "k0: memory {:#x} + {:#x} not handed out (too many ranges)", + gap.base, gap.size + ); + } + Ok(()) + }); + } + + let (mut tables, mut entries, mut bytes, mut ranges) = (0u64, 0u64, 0u64, 0u64); + let mut done = [false; k0_mm::MAX_TABLE_RESERVES]; + loop { + // 아직 처리하지 않은 것 중 가장 큰 구간 + let mut pick: Option = None; + for i in 0..count { + if !done[i] && pick.is_none_or(|p| out[i].size > out[p].size) { + pick = Some(i); + } + } + let Some(i) = pick else { break }; + done[i] = true; + + let (base, size) = (out[i].base, out[i].size); + // 주소 범위의 맨 끝에 걸친 틈은 올림이 넘치므로 온전한 그래뉼이 없는 + // 틈과 같이 다룸(끝 주소는 check_regions가 넘치지 않음을 확인함) + let Some(lo) = base.checked_next_multiple_of(g) else { + continue; + }; + let hi = (base + size) / g * g; + if hi <= lo { + continue; + } + let pages = (hi - lo) / g; + let table_count = k0_mm::alias_tables_for(&(lo..hi)); + let entry_pages = (pages * 8).div_ceil(g); + let share = table_count + entry_pages; + let reason = if pages <= share { + Some("too small for its kernel tables") + } else { + let tail = hi - share * g; + let entry_pa = tail + table_count * g; + if k0_mm::reserve_tables(tail..entry_pa).is_err() { + Some("no kernel tables to map its reserve") + } else if k0_mm::map_kernel_window(entry_pa..hi).is_err() { + Some("its address space entries cannot be mapped") + } else { + // SAFETY: 방금 별칭으로 매핑한 구간이고 untyped에서 빠져 커널만 + // 쓰므로 소거가 다른 것을 덮지 않음. 등록부 접근은 단일 + // 부트 코어의 초기화 시퀀스라 배타적이고, 구간들은 서로 + // 겹치지 않는 틈이며 루트 테이블은 부트 윈도우에 있음 + let added = unsafe { + core::ptr::write_bytes( + (entry_pa + k0_mm::KERNEL_VA_OFFSET) as *mut u8, + 0, + (hi - entry_pa) as usize, + ); + k0_mm::addr_spaces().add_range(lo, pages, entry_pa) + }; + if added { + out[i].size = tail - base; + tables += table_count; + entries += pages; + bytes += share * g; + ranges += 1; + None + } else { + Some("address space registry is full") + } + } + }; + if let Some(why) = reason { + let _ = writeln!(con, "k0: memory {base:#x} + {size:#x} not handed out ({why})"); + out[i].size = 0; + } + } + let _ = writeln!( + con, + "k0: kernel reserve {tables} tables + {entries} address space entries = {bytes:#x} bytes in {ranges} ranges" + ); + + // 넘기지 않기로 한 구간을 빼고 순서를 유지한 채 앞으로 모음 + let mut kept = 0; + for i in 0..count { + if out[i].size != 0 { + out[kept] = out[i]; + kept += 1; + } + } + Ok(kept) +} + /// 루트 CNode의 내용을 bootinfo 페이지에 기록하는 함수입니다. /// /// 페이지는 EL0에 RO로 매핑돼 있고 커널은 TTBR1 별칭으로 씁니다. 0번부터 diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index cd4ca4c..00fbf6e 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -16,12 +16,18 @@ //! [finish]가 한곳에서 합니다. 종료된 태스크의 컨텍스트에는 반환값을 쓰지 //! 않고 소거만 합니다. //! +//! 실행할 태스크가 없어도 커널은 정지하지 않습니다. 현재 태스크가 블록되거나 +//! 종료됐는데 준비된 태스크가 없으면 [idle_until_ready]가 인터럽트를 받으며 +//! 기다리고, 틱마다 기한이 지난 IPC 대기자를 깨웁니다. 그래서 한 태스크가 +//! 마지막으로 블록되는 것만으로는 나머지 태스크의 타임아웃이 멈추지 않습니다. +//! //! # Errors -//! 미지의 시스템 콜 번호와 EL0 폴트는 호출한 태스크만 종료시킵니다. 실행할 -//! 태스크가 남지 않으면 fail-secure 파킹합니다. 케이퍼빌리티 슬롯이나 -//! 사용자 페이지 테이블의 손상은 `k0_arch::fatal`로 정지합니다. +//! 미지의 시스템 콜 번호와 EL0 폴트는 호출한 태스크만 종료시킵니다. +//! 케이퍼빌리티 슬롯이나 사용자 페이지 테이블의 손상은 `k0_arch::fatal`로 +//! 정지합니다. use core::fmt::Write; +use core::sync::atomic::{AtomicBool, Ordering}; use k0_abi::err; use k0_arch::earlycon::EarlyCon; @@ -30,7 +36,6 @@ use k0_cap::{Cap, CapError, CNodeRef, Entry, Mapping, Slot}; use k0_task::{TaskState, Tcb}; use crate::object::{self, Reaper}; -use crate::panic::park; // ABI의 권한 비트와 k0-cap의 권한 비트는 같은 값이어야 함 const _: () = { @@ -46,8 +51,7 @@ const _: () = { /// EL0 svc 트랩의 시스템 콜 정책 함수입니다. (k0-arch가 링크 계약으로 호출) /// -/// 미지의 번호는 제로 트러스트 원칙대로 호출한 태스크를 종료시키고, 그게 -/// 마지막 태스크였다면 fail-secure 파킹합니다. +/// 미지의 번호는 제로 트러스트 원칙대로 호출한 태스크를 종료시킵니다. /// /// # Arguments /// `ctx` - 사용자 컨텍스트, x8 = 번호, x0-x5 = 인자, x0(수신 계열은 x1-x5도) = 반환값 @@ -81,11 +85,24 @@ extern "C" fn k0_syscall(ctx: &mut Context) { nr::CAP_DELETE => Some(sys_cap_delete(a[0])), nr::CAP_REVOKE => Some(sys_cap_revoke(a[0])), // IPC는 블록 경로에서 반환 레지스터를 미래의 상대가 기록하므로 - // 핸들러가 ctx 기록까지 직접 책임지고, false(교착)만 커널이 파킹 - nr::SEND => ipc_or_park(&mut con, k0_ipc::sys_send(ctx)), - nr::RECV => ipc_or_park(&mut con, k0_ipc::sys_recv(ctx)), - nr::CALL => ipc_or_park(&mut con, k0_ipc::sys_call(ctx)), - nr::REPLY_RECV => ipc_or_park(&mut con, k0_ipc::sys_reply_recv(ctx)), + // 핸들러가 ctx 기록까지 직접 책임짐. false는 호출한 태스크가 + // 블록됐는데 준비된 태스크가 없다는 뜻이고, 그때는 커널이 기다림 + nr::SEND => { + let switched = k0_ipc::sys_send(ctx); + ipc_or_idle(ctx, switched) + } + nr::RECV => { + let switched = k0_ipc::sys_recv(ctx); + ipc_or_idle(ctx, switched) + } + nr::CALL => { + let switched = k0_ipc::sys_call(ctx); + ipc_or_idle(ctx, switched) + } + nr::REPLY_RECV => { + let switched = k0_ipc::sys_reply_recv(ctx); + ipc_or_idle(ctx, switched) + } other => { let _ = writeln!(con, "k0: unknown syscall {other}, killing task"); kill_current(); @@ -120,19 +137,25 @@ extern "C" fn k0_fault(ctx: &mut Context, esr: u64, far: u64) { /// 타이머 틱의 선점 정책 함수입니다. (k0-arch가 EL0 IRQ 경로에서 링크 /// 계약으로 호출) +/// +/// 기한이 지난 IPC 대기자를 먼저 깨운 뒤 다음 태스크로 돌립니다. 틱은 실행 +/// 중인 태스크를 끊고 들어왔으므로 현재 태스크는 기한 목록에 없습니다. #[unsafe(no_mangle)] extern "C" fn k0_preempt() { // SAFETY: 벡터가 사용자 컨텍스트 저장을 마친 EL0 IRQ/FIQ 컨텍스트임 - unsafe { k0_sched::rotate() }; + unsafe { + k0_ipc::expire_timeouts(k0_arch::irq::ticks(), None); + k0_sched::rotate(); + } } /// 핸들러가 끝난 뒤의 공통 종료 경로 함수입니다. /// /// 이 시점에는 케이퍼빌리티 삭제에 따른 정리가 전부 끝나 있습니다(k0-cap이 /// 보류 목록을 비운 뒤에 반환함). 현재 태스크가 이번 진입 중에 종료됐으면 -/// 그 컨텍스트를 소거하고 다음 태스크로 넘어갑니다. 준비 큐에는 살아 있는 -/// 태스크만 있으므로(종료 처리가 큐에서 빼냄) 넘어간 태스크가 다시 종료 -/// 상태일 수는 없습니다. +/// 그 컨텍스트를 소거하고 다음 태스크로 넘어갑니다. 준비된 태스크가 없으면 +/// 생길 때까지 기다립니다. 준비 큐에는 살아 있는 태스크만 있으므로(종료 +/// 처리가 큐에서 빼냄) 넘어간 태스크가 다시 종료 상태일 수는 없습니다. /// /// # Arguments /// `ctx` - 이번 진입을 일으킨 태스크의 컨텍스트 @@ -145,9 +168,7 @@ fn finish(ctx: &mut Context, ret: Option) { // 태스크의 컨텍스트이고 그 TCB 프레임은 아직 재사용 전임 *ctx = Context::zeroed(); if !k0_sched::block_and_switch() { - let mut con = EarlyCon; - let _ = writeln!(con, "k0: all tasks exited"); - park() + idle_until_ready(ctx); } return; } @@ -169,18 +190,60 @@ fn kill_current() { unsafe { k0_ipc::teardown(k0_sched::current()) }; } -/// IPC가 교착(전 태스크 블록)을 보고하면 fail-secure 파킹하는 함수입니다. +/// IPC 처리 뒤에, 호출한 태스크가 블록됐는데 준비된 태스크가 없으면 생길 +/// 때까지 기다리는 함수입니다. /// -/// 알림 오브젝트가 생기기 전까지는 블록된 태스크를 깨울 외부 주체가 -/// 없으므로 전 태스크 블록은 회복 불가능한 교착입니다. -fn ipc_or_park(con: &mut EarlyCon, ok: bool) -> Option { - if !ok { - let _ = writeln!(con, "k0: all tasks blocked"); - park() +/// # Arguments +/// `ctx` - 이번 진입을 일으킨 태스크의 컨텍스트 +/// `switched` - IPC 처리 함수의 반환값(false = 블록됐고 전환할 태스크가 없음) +fn ipc_or_idle(ctx: &mut Context, switched: bool) -> Option { + if !switched { + idle_until_ready(ctx); } None } +/// 준비된 태스크가 생길 때까지 인터럽트를 받으며 기다리는 함수입니다. +/// +/// 현재 태스크가 블록됐거나 종료됐는데 준비 큐가 비었을 때 부릅니다. 코어를 +/// 세우지 않고 다음 인터럽트까지 재웠다가, 틱이 지나면 기한이 지난 IPC +/// 대기자를 깨우고 준비된 태스크로 전환합니다. 깨어나는 태스크는 블록된 채 +/// 기다리던 현재 태스크 자신일 수도 있습니다. 지금 태스크를 깨울 수 있는 +/// 것은 타임아웃뿐이라서, 기한을 건 대기자가 하나도 없으면 이 함수는 +/// 돌아오지 않습니다(틱은 계속 처리함). +/// +/// # Arguments +/// `ctx` - 이번 진입을 일으킨 태스크(스케줄러의 현재 태스크)의 컨텍스트 +fn idle_until_ready(ctx: &mut Context) { + static WAITING: AtomicBool = AtomicBool::new(false); + static STOPPED: AtomicBool = AtomicBool::new(false); + let mut con = EarlyCon; + loop { + // 대기에 들어갈 때마다 찍으면 로그를 채우므로 종류마다 처음 한 번만 + // 알림. 기한을 건 대기자가 없는 쪽은 회복할 길이 없는 상태이므로 + // 예전의 정지 메시지와 같은 머리말을 써서 눈에 띄게 함 + // SAFETY: 시스템 콜/폴트 컨텍스트라 스케줄러 접근이 배타적임 + if unsafe { k0_sched::has_timed() } { + if !WAITING.swap(true, Ordering::Relaxed) { + let _ = writeln!(con, "k0: idle (waiting for a timeout)"); + } + } else if !STOPPED.swap(true, Ordering::Relaxed) { + let _ = writeln!(con, "k0: all tasks stopped (none ready, no timeout pending)"); + } + // SAFETY: EL0에서 진입한 예외의 핸들러 안이라 사용자 컨텍스트가 TCB에 + // 저장돼 있고, 커널 스택은 최상단에서 시작해 여유가 있음. + // ctx는 현재 태스크의 컨텍스트이며, 기한이 지난 현재 태스크의 + // 반환값은 이 참조로만 기록됨 + unsafe { + k0_arch::irq::wait_for_interrupt(); + k0_ipc::expire_timeouts(k0_arch::irq::ticks(), Some(&mut *ctx)); + if k0_sched::block_and_switch() { + return; + } + } + } +} + /// 오브젝트의 PA를 커널 별칭 주소로 바꾸는 함수입니다. fn kva(pa: u64) -> u64 { pa + k0_mm::KERNEL_VA_OFFSET @@ -295,7 +358,7 @@ fn sys_retype(ut: u64, kind: u64, dest: u64) -> i64 { let cn = cspace()?; let ut = cn.slot(ut).ok_or(err::BAD_SLOT)?; let dest = cn.slot(dest).ok_or(err::BAD_SLOT)?; - let prep = |pa: u64| -> Option { + let prep = |pa: u64| -> Option { k0_mm::alias_object(pa).ok()?; // SAFETY: 방금 별칭 매핑을 확인한 커널 전용 구간이며, 자손이 없는 // untyped에서만 같은 자리가 다시 나오므로 살아 있는 @@ -321,7 +384,7 @@ fn sys_retype(ut: u64, kind: u64, dest: u64) -> i64 { /// # Errors /// AddrSpace가 아니면 BAD_CAP. 케이퍼빌리티는 있는데 등록부에 없으면 커널 /// 불변식 위반이므로 정지합니다 -fn aspace_of(cn: &CNodeRef, index: u64) -> Result<(*mut Slot, u64, u16, u64), i64> { +fn aspace_of(cn: &CNodeRef, index: u64) -> Result<(*mut Slot, u64, u64, u64), i64> { let (slot, e) = lookup(cn, index)?; let Cap::AddrSpace { root_pa, asid } = e.cap else { return Err(err::BAD_CAP); diff --git a/tools/qemu-boot-test.sh b/tools/qemu-boot-test.sh index d73eb15..871a91a 100755 --- a/tools/qemu-boot-test.sh +++ b/tools/qemu-boot-test.sh @@ -146,7 +146,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: untyped |k0: root cnode ready|k0: bootinfo page ready|k0: user w^x checks pass|k0: entering root task (el0)|root: hello from EL0|root: control byte filter [?]|root: retype/map tests pass|root: capability tests pass|root: untyped reuse test pass|root: child exit test pass|root: ipc tests pass|k0: task fault dabort-lower|k0: task fault fp-simd|root: fault isolation tests pass|root: preempt test pass|root: secret at |root: confined task reported|k0: task fault dabort-lower|root: isolation tests pass|k0: task fault dabort-lower|k0: task fault iabort-lower|k0: task fault dabort-lower|k0: unknown syscall 65535, killing task|root: violation tests pass|root: teardown tests pass|root: revocation tests pass|root: sched tests pass|k0: tick " +markers="k0: entry phase 1 (pre-MMU)|k0: dtb = |k0: mmu on (identity + fixed image address)|k0: jumping to higher half|k0: higher half (pc = |k0: w^x checks pass|k0: memory |k0: platform |k0: root task integrity ok|k0: entropy dtb=|k0: pac=|k0: irq on (timer 1s)|k0: kernel table pool |k0: root task loaded|k0: kernel reserve |k0: untyped |k0: root cnode ready|k0: bootinfo page ready|k0: user w^x checks pass|k0: entering root task (el0)|root: hello from EL0|root: control byte filter [?]|root: retype/map tests pass|root: capability tests pass|root: untyped reuse test pass|root: child exit test pass|root: ipc tests pass|k0: task fault dabort-lower|k0: task fault fp-simd|root: fault isolation tests pass|root: preempt test pass|root: secret at |root: confined task reported|k0: task fault dabort-lower|root: isolation tests pass|k0: task fault dabort-lower|k0: task fault iabort-lower|k0: task fault dabort-lower|k0: unknown syscall 65535, killing task|root: violation tests pass|root: teardown tests pass|k0: idle (waiting for a timeout)|root: timeout tests pass|root: revocation tests pass|root: kernel reserve tests pass|root: sched tests pass|k0: tick " # 메모리의 로그에는 처음 몇 번의 틱만 남습니다. 자가 검증이 그보다 오래 걸리는 # 호스트에서는 끝의 틱이 로그에 없을 수 있으므로 순서 목록에서는 빼고, 첫 틱이 # 기록됐는지와(아래) 자가 검증 뒤에도 틱이 이어지는지를(위의 대기) 따로 봅니다. @@ -193,6 +193,20 @@ if [ -z "$missing" ]; then fi fi +# 타임아웃 n틱은 n주기보다 짧게 끝나면 안 됩니다. EL0에는 시계가 없으므로 틱 +# 줄로 셉니다. 타임아웃 검증은 1틱짜리 대기를 두 번 차례로 끝까지 기다리고 +# (CALL의 응답 기한, 그다음 루트 자신의 수신 기한), 각각 건 뒤 두 번째 틱에서 +# 끝나므로 그 사이에 틱 줄이 적어도 4개 있어야 합니다. 메모리의 로그에는 처음 +# 몇 번의 틱만 남으므로 직렬 판정에서만 셉니다. +if [ -z "$missing" ] && [ -z "$memlog" ]; then + waited="$(tr -d '\r' < "$log" \ + | sed -n '/^root: teardown tests pass/,/^root: timeout tests pass/p' \ + | grep -c '^k0: tick ' || true)" + if [ "$waited" -lt 4 ]; then + missing="at least 4 timer ticks during the timeout tests (found $waited)" + fi +fi + if [ -z "$missing" ] && [ -n "$memlog" ] && ! grep -q '^k0: tick 1$' "$log"; then missing="k0: tick 1" fi diff --git a/userspace/root-task/src/main.rs b/userspace/root-task/src/main.rs index 837aec2..5e7bb7a 100644 --- a/userspace/root-task/src/main.rs +++ b/userspace/root-task/src/main.rs @@ -68,6 +68,11 @@ const PULSE_REPORTER: u64 = 0x4E90; const PULSE_HOLDER: u64 = 0x401D_0000; const PULSE_VIOLATOR: u64 = 0x0710_0000; const PULSE_SURVIVED: u64 = 0x0BAD_0BAD; +/// 타임아웃 검증의 보고 메시지 꼬리표와 pulse 값, 느린 서버의 응답 변환 값 +const TIMED_TAG: u64 = 0x71ED; +const PULSE_TIMED: u64 = 0x0071_0000; +const PULSE_SLOW: u64 = 0x0510_0000; +const SLOW_XOR: u64 = 0x5107; /// EL0가 읽으려 시도할 커널 절반의 주소(커널 이미지가 놓이는 별칭 근처) const KERNEL_PROBE: u64 = k0_abi::KERNEL_IMAGE_VA; @@ -546,6 +551,41 @@ extern "C" fn reporter_entry(mode: u64) -> ! { } } +/// 1번 엔드포인트에서 기한을 건 연산 하나를 하고 그 반환 코드를 2번 +/// 엔드포인트로 보고하는 격리 태스크의 진입점입니다. +/// +/// # Arguments +/// `arg` - 하위 8비트는 연산(0 = RECV, 1 = SEND, 2 = CALL), 그 위는 타임아웃 +/// 틱 수 +extern "C" fn timed_entry(arg: u64) -> ! { + let (mode, ticks) = (arg & 0xFF, (arg >> 8) as u32); + pulse(PULSE_TIMED + mode); + let flags = ipc::timeout(ticks); + let status = match mode { + 0 => recv(1, flags).status, + 1 => send(1, flags, [0x71, 0, 0, 0]).status, + _ => call(1, flags, [0x7C, 0, 0, 0]).status, + }; + send(2, 0, [status as u64, TIMED_TAG, mode, 0]); + loop { + yield_now(); + } +} + +/// 첫 CALL을 받은 뒤 2번 엔드포인트의 신호를 기다렸다가 응답하는 격리 서버의 +/// 진입점입니다. +/// +/// 신호가 오기 전에 호출자의 기한이 지나게 해서, 뒤늦은 응답이 버려지고 +/// 서버는 그 뒤의 호출에 정상으로 응답하는지 검증합니다. +extern "C" fn slow_server_entry(_arg: u64) -> ! { + let mut r = recv(1, 0); + pulse(PULSE_SLOW + r.mr[0]); + recv(2, 0); + loop { + r = reply_recv(1, 0, [r.mr[0] ^ SLOW_XOR, 0, 0, 0]); + } +} + /// CALL 하나를 받고 응답하지 않은 채 머무는 격리 서버의 진입점입니다. 응답 /// 자격을 쥔 태스크가 삭제되는 경로를 검증합니다. extern "C" fn holder_entry(_arg: u64) -> ! { @@ -742,6 +782,7 @@ extern "C" fn _start() -> ! { test_reuse(&b); test_sched_ipc_fault(&b); test_isolation(&b); + test_reserve(&b); put_str("root: sched tests pass\n"); loop { @@ -1598,6 +1639,16 @@ fn test_isolation(b: &Boot) { put_str("root: violation tests pass\n"); test_teardown(&iso, q); + // 타임아웃 검증의 오브젝트는 가장 큰 untyped에서 잘라, 이 작은 untyped가 + // 대야 하는 프레임 수를 늘리지 않음. 태스크는 같은 주소 공간에서 실행되므로 + // 아래의 회수가 그 주소 공간을 없앨 때 함께 종료됨 + let timed_iso = Iso { + ut: b.ut_main, + fs, + aspace, + pulse_view, + }; + test_timeouts(&timed_iso, q); // CNode 회수: 태스크에 묶인 케이퍼빌리티 공간이 사라지면 그 태스크는 // 종료됨. 송신이 거부될 뿐 계속 실행된다면 pulse가 계속 바뀜 @@ -1860,6 +1911,155 @@ fn test_teardown(iso: &Iso, q: i64) { put_str("root: teardown tests pass\n"); } +/// 커널의 별칭 테이블과 주소 공간 등록부가 untyped를 쥔 태스크에게 바닥나지 +/// 않는 것을 검증하는 함수입니다. +/// +/// 예전 커널은 별칭 테이블을 정적 풀 40장에서, 주소 공간 번호를 256칸짜리 +/// 표에서 내주었습니다. 그래서 untyped를 넉넉히 쥔 태스크 하나가 둘 다 바닥내 +/// 다른 모든 태스크의 재분류를 실패시킬 수 있었습니다. 지금은 둘 다 부팅 때 +/// 메모리 크기에 맞춰 잡습니다. 다른 검증이 끝난 뒤에 가장 큰 untyped를 써서 +/// 예전 한계를 넘겨 봅니다. +fn test_reserve(b: &Boot) { + let (ut, fs) = (b.ut_main, b.frame_size); + let tmp = alloc_slot(); + + // 주소 공간 300개가 동시에 살아 있음. 루트 CNode에는 그만한 빈 슬롯이 + // 없으므로 만든 것을 새 CNode들로 옮겨 둠 + const NODES: usize = 5; + const PER_NODE: u64 = 60; + let mut nodes = [0i64; NODES]; + for n in nodes.iter_mut() { + *n = retype(ut, obj::CNODE); + check("reserve cnode", *n > 0); + } + for &cn in &nodes { + for i in 1..=PER_NODE { + check("address space beyond 256", retype_at(ut, obj::ADDR_SPACE, tmp) == 0); + check("park address space", cap_move(tmp as i64, cn, i) == 0); + } + } + // CNode를 지우면 그 안의 주소 공간이 함께 종료되고 등록부 항목이 풀림 + for &cn in &nodes { + check("drop address spaces", cap_delete(cn) == 0); + } + check( + "address space after the burst", + retype_at(ut, obj::ADDR_SPACE, tmp) == 0 && cap_delete(tmp as i64) == 0, + ); + + // 프레임을 하나씩 재분류하며 untyped를 따라 올라감. 재분류마다 커널이 그 + // 그래뉼의 별칭을 만들고, 최하위 테이블 하나가 덮는 구획(4K 그래뉼에서 + // 2MiB)을 넘을 때마다 테이블이 한 장 더 듦. 예전 풀의 여유는 24장 + // 남짓이었으므로 40구획을 넘기면 반드시 바닥났음. untyped가 그보다 작은 + // 배치에서는 끝까지 감 + let per_table = fs / 8; + let mut walked = 0u64; + while walked < 40 * per_table { + let r = retype_at(ut, obj::FRAME, tmp); + if r == err::EXHAUSTED { + break; + } + check("alias tables never run out", r == 0); + check("drop walked frame", cap_delete(tmp as i64) == 0); + walked += 1; + } + // untyped가 테이블 한 장 분량보다 작은 배치에서는 끝까지 간 것으로 충분함 + check("walked some frames", walked > 0); + put_str("root: kernel reserve tests pass\n"); +} + +/// IPC 타임아웃과, 모든 태스크가 블록돼도 커널이 멈추지 않는 것을 검증하는 +/// 함수입니다. +/// +/// 틱 주기가 1초라서 기한을 기다리는 단계마다 1초에서 2초가 걸립니다. 그래서 +/// 여러 대기자를 같은 틱에 겹쳐 놓습니다. +/// +/// # Arguments +/// `q` - 격리 태스크들이 보고에 쓰는 엔드포인트 +fn test_timeouts(iso: &Iso, q: i64) { + let (ut, nb) = (iso.ut, ipc::NONBLOCK); + let timed = timed_entry as usize as u64; + let lone = retype(ut, obj::ENDPOINT); + check("timeout lone ep", lone > 0); + + // 뜻이 정해지지 않은 플래그 비트는 거부되고, 비대기 플래그는 타임아웃보다 + // 우선함 + check("flag bit 1 refused", recv(lone, 2).status == err::BAD_FLAGS); + check("flag bit 31 refused", send(lone, 1 << 31, [0; 4]).status == err::BAD_FLAGS); + check("flag bits refused on call", call(lone, nb | 4, [0; 4]).status == err::BAD_FLAGS); + check( + "flag bits refused on reply_recv", + reply_recv(lone, 0x100, [0; 4]).status == err::BAD_FLAGS, + ); + check( + "nonblock beats timeout", + recv(lone, nb | ipc::timeout(9)).status == err::WOULD_BLOCK, + ); + + // 느린 서버와, 상대가 없는 엔드포인트에서 기한을 걸고 기다리는 세 태스크 + // (수신, 송신, 수신자를 기다리는 CALL) + let (srv_ep, go) = (retype(ut, obj::ENDPOINT), retype(ut, obj::ENDPOINT)); + check("slow server eps", srv_ep > 0 && go > 0); + iso.spawn( + slow_server_entry as usize as u64, + 0, + &[(srv_ep, rights::R, 0), (go, rights::R, 0)], + ); + for mode in 0..3u64 { + let ep = retype(ut, obj::ENDPOINT); + check("timed ep", ep > 0); + let need = if mode == 0 { rights::R } else { rights::W }; + iso.spawn(timed, mode | (1 << 8), &[(ep, need, 0), (q, rights::W, 0)]); + } + + // 루트는 서버에 기한을 걸고 CALL함. 서버는 메시지를 받고 신호를 기다리며 + // 블록되고 세 태스크도 각자 블록되므로 실행할 태스크가 하나도 남지 않음. + // 예전 커널은 여기서 코어를 세웠음. 이제는 틱을 기다렸다가 기한이 지난 + // 대기자를 깨우고, 루트는 메시지가 전달된 뒤였으므로 REPLY_TIMEOUT을 받음 + let r = call(srv_ep, ipc::timeout(1), [1, 0, 0, 0]); + check("call reply timeout", r.status == err::REPLY_TIMEOUT); + + // 세 태스크는 전부 TIMEOUT으로 깨어나 보고함. 아직 기한 전이면 루트는 + // 기한 없이 기다리고, 그동안에도 틱이 그들을 깨움 + let mut seen = 0u64; + for _ in 0..3 { + let r = recv(q, 0); + check( + "timed report", + r.status == 0 && r.mr[1] == TIMED_TAG && r.mr[0] == err::TIMEOUT as u64 && r.mr[2] < 3, + ); + seen |= 1 << r.mr[2]; + } + check("all three timed out", seen == 0b111); + + // 서버의 뒤늦은 응답은 받을 상대가 없어 버려지고, 서버는 다음 호출에 + // 그 호출의 응답을 돌려줌(첫 호출의 응답이 섞여 오지 않음) + check("release slow server", send(go, 0, [0; 4]).status == 0); + let r = call(srv_ep, 0, [2, 0, 0, 0]); + check("late reply dropped", r.status == 0 && r.mr[0] == 2 ^ SLOW_XOR); + + // 기한을 건 채 블록된 태스크의 삭제: 기한 목록에서 빠지므로, 그 기한이 + // 지나는 뒤의 틱에서 커널이 사라진 TCB를 따라가지 않음 + let gone_ep = retype(ut, obj::ENDPOINT); + check("gone ep", gone_ep > 0); + let g = iso.spawn(timed, 1 << 8, &[(gone_ep, rights::R, 0), (q, rights::W, 0)]); + check("timed waiter arrived", iso.wait_pulse(PULSE_TIMED)); + yield_now(); + check("delete timed waiter", cap_delete(g.tcb) == 0); + + // 기한 전에 메시지로 깨어난 대기자의 기한은 취소됨. 남아 있었다면 바로 + // 다음의 기한 있는 대기에서 커널이 이중 등록을 발견하고 정지함. 이 + // 시점에는 앞의 세 태스크가 양보 루프를 돌고 있으므로 기한 처리는 대기 + // 루프가 아니라 선점 경로에서 일어남 + let b = iso.spawn(blocker_entry as usize as u64, 77, &[(q, rights::W, 0)]); + let r = recv(q, ipc::timeout(1)); + check("woken before deadline", r.status == 0 && r.mr == [0xB10C, 77, 0, 0]); + check("own recv times out", recv(lone, ipc::timeout(1)).status == err::TIMEOUT); + check("deleted waiter stayed gone", recv(q, nb).status == err::WOULD_BLOCK); + check("delete blocker", cap_delete(b.tcb) == 0); + put_str("root: timeout tests pass\n"); +} + #[panic_handler] fn panic(_info: &PanicInfo) -> ! { let _ = sys1(syscall::EXIT, 1);